How to make a default value for the struct in C#?

前端 未结 5 1467
猫巷女王i
猫巷女王i 2021-01-07 20:36

I\'m trying to make default value for my struct. For example default value for Int - 0, for DateTime - 1/1/0001 12:00:00 AM. As known we can\'t define parameterless constru

5条回答
  •  半阙折子戏
    2021-01-07 21:11

    You can also do this:

    public struct MyStruct
    {
        public static readonly Default = new MyStruct(42);
    
        public int i;
    
        public MyStruct(int i)
        {
            this.i = i;
        }
    }
    

    And then when you create a default struct of this type do this:

    public MyStruct newStruct = MyStruct.Default;
    

    But of course, this won't override default and other programmers will bump their heads a few times. Really consider if a struct is the way to go, from the microsoft docs:

    "A structure type (or struct type) is a value type that can encapsulate data and related functionality. Typically, you use structure types to design small data-centric types that provide little or no behavior."

    Consider this: if you had 2 values in your struct and you wanted to make constructors, would 2 or less constructors suffice? If the answer is no, then the answer is: don't use a struct.

提交回复
热议问题