ヘッダー
C# サンプル集
 

構造体の宣言

2021/4/18

→ Visual Basic のサンプルに切り替える

 

 

一般的な構造体

public struct SampleStruct
{
    public string Field1; //フィールド
    public int  Prop1 {get; set;} //プロパティ。 この構文でプロパティを宣言できるのはC#2.0(2005年)以上。

    //コンストラクター
    public SampleStruct(string initValue) : this()
    {
        Field1 = initValue;
    }

    //メソッド
    public int Add(int x, int y)
    {
        return x + y;
    }
}

 

 

型パラメーターを持つ構造体(ジェネリック)

public struct SampleStruct<T>
{
    public T X;
    public T Y;
    public T Z;
}

使用例

SampleStruct<decimal> s1;
s1.X = 100;
s1.Y = 200;

SampleStruct<string> s2;
s2.X = "AAA";
s2.Y = "BBB";

 

 

型パラメーターを2つ持つ構造体(ジェネリック)

public struct SampleStruct<T1, T2>
{
    public T1 X;
    public T2 Y;
}

使用例

SampleStruct<decimal, string> s1;
s1.X = 100;
s1.Y = "AAA";

SampleStruct<bool, DateTime> s2;
s2.X = true;
s2.Y = new DateTime(2024, 6, 27);

 

 

読み取り専用の構造体(readonly構造体)

public readonly struct SampleStruct
{
    public readonly string Field1;
    public int  Prop1 {get;} 
    public string Prop2 {get; init;} 
}

メモ:C# 7.2(2017年8月)以降で使用可能です。通常の構造体よりパフォーマンスが向上します。

 

 

ref構造体

public ref struct SampleStruct
{
    public Span<int> Buffer1; 
    public ReadOnlySpan<int> Buffer2;
}

メモ:C# 7.2(2017年8月)以降で使用可能な特殊な構造体です。Span<T>、ReadOnlySpan<T>をメンバーに持つことができるようになりますが、多くの制約が課されます。

 

 

参考

構造体型 - C# リファレンス | Microsoft Docs

クラスと構造体 - C# プログラミング ガイド | Microsoft Docs