How to make default value for struct C #?

I am trying to make a default value for my structure. For example, the default value for Int is 0, for DateTime it is 1/1/0001 12:00:00 AM As you know, we cannot define a constructor without parameters in the 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 the default value for struct?

+4
source share
5 answers

You can not. Structures are always pre-zeroed, and there is no guarantee that the constructor is ever called (for example, new MyStruct[10]). If you need non-zero defaults, you need to use a class. This is why you cannot change the default constructor in the first place (before C # 6) - it never executes.

, , Nullable , - , null :

public struct MyStruct
{
  int? myInt;

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

myInt - , "" ( 42). , :)

Console.WriteLine, ToString. , , .

+7

#/. Net. -.

Console.WriteLine ToString(). (Object.ToString()) ( , ).

, ToString:

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

# , .ToString() . , , ?

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

PS: default (Test) , default (int) default (string), Test.num is 0 Test.str is null

,

+1

, , , ToString(), .

struct Test
{
    int num;
    string str;

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

As you already mentioned, it is not possible to define default values ​​for fields other than default values ​​for their respective types. However, when exceeded, ToString()you will see the best formatted information about your structure in the console and during debugging.

0
source

You can initialize structas follows:

struct Test
    {
        public int num;
        public string str;
    };

 static void Main(string[] args)
    {
            Test tdefault = new Test{ num = 1, str = "" };
            Test t = tdefault;
    }
0
source

Source: https://habr.com/ru/post/1656663/


All Articles