0

In C# the default keyword can be used to get the default value of a given type:

enum E1 { A,B,C,D }
enum E2 { A=1,B=2,C=3,D=4 }

int i = default(int);         // i = 0
MyClass c = default(MyClass); // c = null
E1 e1 = default(E1);          // e1 = A;
E2 e2 = default(E2);          // e2 = 0;

But sometimes, getting a null as a default value for a class is not convenient (and also some coders have the opinion that returning null is not the best choice).

Suppose that I want to return a well-known and controlled instance of MyClass as the result of the expression default(MyClass), for example:

class MyClass
{
    // Default value.
    private static MyClass default_value = new MyClass();
    // Default 'converter'.
    public MyClass() {  }

    // Default 'converter'... I've tried: it doesn't work.
    public MyClass default { return default_value; }
}

MyClass c = default(MyClass); // c = MyClass.default_value

AfaIk there's no way to customize the way the default keyword works to achieve the behaviour I want but anyways I'm not a C# expert so the question is:

  • Is there any C# construct or workarround to customize the default keyword behaviour when used over a custom type?
PaperBirdMaster
  • 12,806
  • 9
  • 48
  • 94
  • It would probably be better (for you and anyone using your code down the road) to simply add a static method to return what you consider a 'default' instance e.g. `MyClass defInstance = MyClass.Default;` Once you start down the rabbit hole of trying to redefine expected behavior from built-in keywords, you'll only create a headache for everyone involved. – Nate222 Oct 22 '15 at 09:39
  • @Nate222 but with a static method or property we cannot use the value in generics code. `void f() { T t = default(T); /* play with t... */ print(t.ToString()); }` – PaperBirdMaster Oct 22 '15 at 09:44
  • You're right about default and generics. But - you're also out of luck. – Nate222 Oct 22 '15 at 09:50

0 Answers0