Home > database >  Const or static property on record type in C#
Const or static property on record type in C#

Time:10-20

I have a record type

record Test(int Magic);

and I want to define some constant value that is not required to be configurable e.g. so I can access it like this

Test.MyMagicConst

In F# I can use modules to define a constant under the same name as a record type.

Is that possible to achieve something similar in C# and records?

CodePudding user response:

Yes. You can add additional properties inside the definition of the record:

public record Test(int Magic)
{
    public const int MyMagicConst = 10;
}

CodePudding user response:

A few options, a const field, or a static readonly field, or a static property

  1. a const field for simple types

    public record Test(int Magic)
    {
        public const int MyMagicConst = 100;
    }
    
  2. static readonly field for more complex types

    public record Test(int Magic)
    {
        public static readonly int MyMagicConst = 100;
    }
    
  3. static property for when you need some calculations done first

    public record Test(int Magic)
    {
        public static int MyMagicConst {get => IsHardCore ? 10 :100; }
    }
    
  •  Tags:  
  • c#
  • Related