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?