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 constructor in structure.
struct Test { int num; string str; } class Program { static void Main(string[] args) { Console.WriteLine(default(Test)); // shows namespace and name of struct test.Test Console.WriteLine(new Test()); // same Console.ReadKey(true); } }
How can I make a default value for struct?
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members. Another way of assigning default values to structs is by using tags.
For variables of class types and other reference types, this default value is null . However, since structs are value types that cannot be null , the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null .
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
The direct answer is because the structure definition declares a type and not a variable that can be initialized. Your example is: struct s { int i=10; }; This does not declare any variable - it defines a type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With