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

前端 未结 5 1473
猫巷女王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:16

    What you probably want to do is to override ToString(), e.g.

    struct Test
    {
        int num;
        string str;
    
        public override string ToString ()
        {
            return string.Format ($"{str} | {num}");
        }
    }
    

    As you have mentioned, it is impossible to define default values for fields other than default values for their appropriate types. However, with an overriden ToString(), you will see better formatted information about your structure in the console and during debugging.

提交回复
热议问题