LoginSignup
8
9

More than 1 year has passed since last update.

Visual Studio2022でC#のコードスニペットを使ってみる

Posted at

1. はじめに

  • Visual Studio 2022でC#の開発をする時に同じコードはスニペットを使って効率化したい
  • プロジェクト内のコーディングルールを独自にスニペットに追加したい

2. コードスニペットとは

2.1. コードスニペット

  • あらかじめ用意されているコードのスニペットで、コードにすぐに挿入することができる

2.2. コードスニペットの利用例(for文)

  • コードでforを入力して、Tabキーを2回押す
    image.png

  • for文のコードが挿入される
    image.png

3. 既定のコードスニペット

  • 既定では、Visual Studio の C# には次のコード スニペットが含まれる

3.1. #if

#if true

#endif

3.2. #region

#region MyRegion

#endregion

3.3. ~

~HogeClass()
{
                
} 

3.4. attribute

[AttributeUsage(global::System.AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
    // See the attribute guidelines at 
    //  http://go.microsoft.com/fwlink/?LinkId=85236
    readonly string positionalString;

    // This is a positional argument
    public MyAttribute(string positionalString)
    {
        this.positionalString = positionalString;

        // TODO: Implement code here

        throw new NotImplementedException();
    }
}

3.5. checked

checked
{

}

3.6. class

class MyClass
{

}

3.7. ctor

public HogeClass()
{
          
}

3.8. cw

Console.WriteLine();

3.9. do

do
{

} while (true);

3.10. else

else
{

}

3.11. enum

enum MyEnum
{

}

3.12. equals

public override bool Equals(object obj)
{
    //       
    // See the full list of guidelines at
    //   http://go.microsoft.com/fwlink/?LinkID=85237  
    // and also the guidance for operator== at
    //   http://go.microsoft.com/fwlink/?LinkId=85238
    //

    if (obj == null || GetType() != obj.GetType())
    {
        return false;
    }

    // TODO: write your implementation of Equals() here
    throw new NotImplementedException();
    return base.Equals(obj);
}

3.13. exception

[global::System.Serializable]
public class MyException : Exception
{
    public MyException() { }
    public MyException(string message) : base(message) { }
    public MyException(string message, Exception inner) : base(message, inner) { }
    protected MyException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}

3.14. for

for (int i = 0; i<length; i++)
{

}

3.15. foreach

foreach (var item in collection)
{

}

3.16. forr

for (int i = length - 1; i >= 0; i--)
{

}

3.17. if

if (true)
{

}

3.18. indexer

public object this[int index]
{
    get { /* return the specified index here */ }
    set { /* set the specified index to value here */ }
}

3.19. interface

interface IInterface
{

}

3.20. invoke

EventHandler temp = MyEvent;
if (temp != null)
{
    temp();
}

3.21. iterator

public System.Collections.Generic.IEnumerator<ElementType> GetEnumerator()
{

    throw new NotImplementedException();
    yield return default(ElementType);
}

3.22. iterindex

public MyViewIterator MyView
{
    get
    {
        return new MyViewIterator(this);
    }
}

public class MyViewIterator
{
    readonly MyViewIterator outer;

    internal MyViewIterator(MyViewIterator outer)
    {
        this.outer = outer;
    }

    // TODO: provide an appropriate implementation here
    public int Length { get { return 1; } }

    public ElementType this[int index]
    {
        get
        {
            //
            // TODO: implement indexer here
            //
            // you have full access to MyViewIterator privates
            //

            throw new NotImplementedException();
            return default(ElementType);
        }
    }

    public System.Collections.Generic.IEnumerator<ElementType> GetEnumerator()
    {
        for (int i = 0; i < this.Length; i++)
        {
            yield return this[i];
        }
    }
}        

3.23. lock

lock (this)

{

}

3.24. mbox

MessageBox.Show("Test");

3.25. namespace

namespace MyNamespace
{

}

3.26. prop

public int MyProperty { get; set; }

3.27. XXXX

private int myVar;

public int MyProperty
{
    get { return myVar; }
    set { myVar = value; }
}

3.28. propg

public int MyProperty { get; private set; }

3.29. sim

static int Main(string[] args)
{

    return 0;
}

3.30. struct

struct MyStruct
{

}

3.31. XXXX

static void Main(string[] args)
{

}

3.32. switch

switch (switch_on)
{
    default:
}

3.33. try

try 
{	        
		
}
catch (global::System.Exception)
{

	throw;
}

3.34. unchecked

unchecked
{

}

3.35. unsafe

unsafe
{

}

3.36. using

using (resource)
{

}

3.37. while

while (true)
{

}

4. 独自のコードスニペットの登録

4.1. Visual Studio Snippet Generator

  • 下記URLへアクセスする

  • ShortCut, Codeは必須で入力し、Generate、Downloadボタンの順にクリックする
    image.png

    • $end$ は、コード スニペットが挿入された後にカーソルを置く場所を示す
    • $selected$ は、呼び出されたときにスニペットに挿入されるドキュメントで選択されたテキストを表す
  • ダウンロードしたファイルを任意のフォルダに格納する
    image.png

4.2. Visual Studioへのスニペット取り込み

  • [ツール] > [コードスニペットマネージャー]を選択する
    image.png

  • 言語はCSharp、場所はMyCodeSnippetを選択して、インポートボタンをクリックする
    image.png

  • Generateしたファイルを開く
    image.png

* 完了ボタンをクリックする
image.png

4.3. Visual Studioでの動作確認

  • dpを入力し、Tabキーを2回クリックする
    image.png

  • コードが表示されることを確認
    image.png

4.3. コードスニペットの削除

  • GUIで削除することができないため、フォルダの場所を直接開いてファイルを消す
    image.png

image.png

5. 参考文献

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9