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

This is my take on this in case somebody finds it useful.

public struct MyStruct
{
    public int item1;
    public float item2;
    public float item3;

    public static MyStruct Null => new MyStruct(-1, 0, 0);
}

I have a static method inside my struct so that I can do this:

var data = MyStruct.Null;

instead of

var data = new MyStruct();
data.item1 = -1;
...

Or create a custom constructor to pass the data.


Your problem is not with the behaviour of C#/.Net. The way you instantiate the struct effectively creates an instance with default values for all member fields.

The Console.WriteLine converts its argument to a string using the ToString() method. The default implementation (Object.ToString()) simply writes the fully qualified class name (namespace and name, as you call it).

If you want another visualisation, you should override the ToString method:

public struct Test
{
    int num;
    string str;
    public override string ToString()
    {
        return $"num: {num} - str: {str}";
    } 
}

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.


Printing out objects of the C# results with namespaces unless you override .ToString() for your objects. Can you define your struct like below and try it ?

public struct Test
{
    int num;
    string str;
    public override string ToString()
    {
        return "Some string representation of this struct";
    }
}

PS: default(Test) gives you a struct contains default(int) and default(string) which I mean Test.num is 0 and Test.str is null

Hope this helps

Tags:

C#

Struct