LoginSignup
198
230

More than 1 year has passed since last update.

【C#】コレの名前、なんだっけ?【用語集】

Posted at

C#で名称を忘れやすい語句について、簡単な解説・用例とともにまとめました。
実装やコードレビューなどの場面でお役に立てば幸いです。

/// ドキュメンテーションコメント

クラスやメンバーの説明を記述するのに利用する。

/// <summary>
///  This class performs an important function.
/// </summary>
public class MyClass {}

@ 逐語的識別子

先頭に付加することで、例外的に予約語を識別子とすることができる。

string @string = "John";
Console.WriteLine(@string); // John

@"" 逐語的文字列リテラル

\をエスケープシーケンスと見なさず、そのままの表記で解釈する。

string filename = @"c:\documents\files\u0066.txt";
Console.WriteLine(filename); // c:\documents\files\u0066.txt

$"{}" 文字列補間

{}の中が式として解釈され、その結果の文字列表現で置き換えられる。

string name = "Mark";
Console.WriteLine($"Hello, {name}!"); // Hello, Mark!

T? Null許容値型(Nullable型)

値型Tでnullを表現したい場合に利用する。

int? num = null;
bool? flag = null;

?. Null条件演算子

aがnullの場合、a?.xの結果はnullとなる。
aがnull以外の場合、a?.xの結果はa.xの結果と同様となる。

string str1 = "test";
Console.WriteLine(str1?.Length); // 4
Console.WriteLine(str1.Length); // 4

string str2 = null;
Console.WriteLine(str2?.Length); //
Console.WriteLine(str2.Length); // System.NullReferenceException

! Null免除演算子

式がnullでないことを明示し、コンパイラに対して警告を免除させる。

public static void Main()
{
    Person? p = Find("John");
    if (IsValid(p))
    {
        Console.WriteLine($"Found {p!.Name}");
    }
}

public static bool IsValid(Person? person)
    => person is not null && person.Name is not null;

^m 末尾からのインデックス演算子

末尾からm番目の要素を示す。たとえば、^1は最後の要素を示す。

var lines = new List<string> { "one", "two", "three", "four" };
Console.WriteLine(lines[^2]);  // three

m..n 範囲演算子

m~n番目の要素(ただし、n番目を含まない)を示す。

int[] numbers = new[] { 0, 10, 20, 30, 40, 50 };
int[] subset = numbers[1..4];
Console.WriteLine(string.Join(" ", subset)); // 10 20 30

[][] ジャグ配列

要素ごとにサイズが異なる(不揃いな)多次元配列。

int[][] jaggedArray = new int[][]
{
    new int[] { 1, 3, 5, 7, 9 },
    new int[] { 0, 2, 4, 6 },
    new int[] { 11, 22 }
};

++ インクリメント演算子

オペランドに対して、1を加算する。

int i = 3;
i++;
Console.WriteLine(i); // 4

-- デクリメント演算子

オペランドに対して、1を減算する。

int i = 3;
i--;
Console.WriteLine(i); // 2

?: 条件演算子(三項演算子)

条件式の評価結果(真偽)に応じて、2つの式のいずれかの結果を返す。

string GetWeather(double temp) => temp < 20.0 ? "Cold." : "Perfect!";
Console.WriteLine(GetWeather(15));  // Cold.
Console.WriteLine(GetWeather(27));  // Perfect!

?? Null合体演算子

左側のオペランドがnullでない場合には、左側のオペランドの値を返す。
左側のオペランドがnullの場合には、右側のオペランドの値を返す。

int a = 2;
int? b = null;
Console.WriteLine(a ?? -1);  // 2
Console.WriteLine(b ?? -1);  // -1

??= Null合体代入演算子

左側のオペランドがnullの場合のみ、右側のオペランドの値を左側のオペランドに代入する。

List<int> numbers = null;
(numbers ??= new List<int>()).Add(5);
Console.WriteLine(string.Join(" ", numbers));  // 5

# プリプロセッサディレクティブ

他のコードと区別するために、#で始まるキーワード。コンパイラに対する命令を表す。

#define DEBUG

#if DEBUG
   Console.WriteLine("DEBUG");
#endif

{} オブジェクト初期化子コレクション初期化子

オブジェクトやコレクションをインスタンス化するタイミングで、まとめてメンバーを割り当てる。

// オブジェクト初期化子
Cat cat = new Cat { Age = 10, Name = "Fluffy" };

// コレクション初期化子
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };  

// インデックス初期化子
var planet = new Dictionary<string, string>
{
    ["Earth"] = "地球",
    ["Jupiter"] = "木星",
    ["Mercury"] = "水星"
};

~ ファイナライザー

オブジェクトが破棄されるタイミングで自動的に実行される。

class Car
{
    ~Car()  // finalizer
    {
        // cleanup statements...
    }
}

new {} 匿名型

new演算子とオブジェクト初期化子{}を使用することで、名前のない型を初期化することができる。

var v = new { Amount = 108, Message = "Hello" };
Console.WriteLine(v.Amount); // 108
Console.WriteLine(v.Message); // Hello

{ get; set; } 自動実装プロパティ

アクセサ(get/set)に特別なロジックが必要ないときに、プロパティを簡潔に宣言できる。

public class Customer
{
    public string Name { get; set; } 
    public int CustomerId { get; set; }

    public Customer(string name, int id)
    {
        Name = name;
        CustomerId = id;
    }
}

参考サイト

198
230
2

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
198
230