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

前端 未结 5 1461
猫巷女王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条回答
  •  Happy的楠姐
    2021-01-07 20:57

    You can't. Structures are always pre-zeroed, and there is no guarantee the constructor is ever called (e.g. new MyStruct[10]). If you need default values other than zero, you need to use a class. That's why you can't change the default constructor in the first place (until C# 6) - it never executes.

    The closest you can get is by using Nullable fields, and interpreting them to have some default value if they are null through a property:

    public struct MyStruct
    {
      int? myInt;
    
      public int MyInt { get { return myInt ?? 42; } set { myInt = value; } }
    }
    

    myInt is still pre-zeroed, but you interpret the "zero" as your own default value (in this case, 42). Of course, this may be entirely unnecessary overhead :)

    As for the Console.WriteLine, it simply calls the virtual ToString. You can change it to return it whatever you want.

提交回复
热议问题