6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C#】地味に便利な機能まとめ

6
Last updated at Posted at 2024-12-29

はじめに

C#には普段何気なく使っている便利な機能がたくさんあります。この記事では、日々の開発で役立つ地味だけど便利な機能をまとめてみました。

以下で紹介した内容と重なる機能もあるかもですが、個人にはスニペット(Tab補完)機能は好きでかなり使っているので、それらも入れて改めてまとめました。

コード入力支援機能

Visual Studioなどのエディタで利用できる入力支援機能です。

スニペット(Tab補完)機能

// if + Tab + Tab で展開
if (condition)
{
    
}

// ctor + Tab + Tab でコンストラクタ
public ClassName()
{
    
}

// prop + Tab + Tab でプロパティ
public Type PropertyName { get; set; }

// propfull + Tab + Tab で完全なプロパティ
private Type propertyName;
public Type PropertyName
{
    get { return propertyName; }
    set { propertyName = value; }
}

便利な構文機能

null関連の機能

// nullチェック付き代入(null合体演算子)
string value = someString ?? "デフォルト値";

// null条件演算子
int? length = someString?.Length;

switch式

string message = value switch
{
    0 => "ゼロです",
    1 => "イチです",
    _ => "その他です"
};

using宣言

// 自動でDisposeされる
using var reader = new StreamReader(path);

文字列補間

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

地味だけど役立つ機能たち

default式の型推論

// 型指定が不要になり、コードがスッキリ
Dictionary<string, List<int>> dict = default;

配列初期化の省略記法

// 型指定が不要
var array = new[] { 1, 2, 3 };

out変数の宣言

// 従来の書き方
int number;
if (int.TryParse("123", out number)) { }

// C# 7.0以降
if (int.TryParse("123", out int number)) { }

タプル構文

(string name, int age) GetPerson()
{
    return ("John", 30); // 明示的なタプル作成が不要
}

オーバーフロー制御

// オーバーフローを検出する
checked
{
    int result = Int32.MaxValue + 1; // OverflowExceptionが発生
}
// オーバーフローを無視する
unchecked
{
    int result = Int32.MaxValue + 1; // オーバーフローを許可
}

イニシャライザでのプロパティ設定

var person = new Person 
{
    Name = "John",
    Age = 30
}; // コンストラクタを作らなくても初期化できる

プロパティの必須化

// オブジェクト初期化時に必須プロパティを強制
public class Employee
{
    public required string Name { get; init; }
    public required int EmployeeId { get; init; }
}

パターンマッチングでのwhen

if (obj is string str when str.Length > 5)
{
    // 型チェックと条件チェックを1行で
}

スレッドセーフなシングルトン

private static readonly Lazy<MyClass> _instance = 
    new Lazy<MyClass>(() => new MyClass());

名前付き引数

// パラメータの順序を気にせず指定可能
Calculate(height: 180, weight: 70);

部分的なusing

using static System.Math; // Mathのメソッドを直接使える
var result = Sqrt(16); // Math.Sqrt()と書かなくて良い

破棄パターン

var (first, _, third) = tuple; // 不要な値を破棄できる

まとめ

この記事で紹介した機能は、C#の基本的な機能の一部ですが、適切に使用することでコードの可読性と保守性を向上させることができます。日々の開発で取り入れていただければ嬉しいです。

参考

6
7
4

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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?