views:

216

answers:

6

I see some code will return default value, so i am wondering for a user defined class, how will the compiler define its default value?

+4  A: 

The default value for class is a null

Ngu Soon Hui
+1  A: 

If it is a reference type, the default value will be null, if it is a value type, then it depends.

Darin Dimitrov
+10  A: 

To chime in with the rest, it will be null, but I should also add that you can get the default value of any type, using default

default(MyClass) // null
default(int) // 0

It can be especially useful when working with generics; you might want to return default(T), if your return type is T and you don't want to assume that it's nullable.

David Hedlund
+1 There is a full explanation of the default keyword at http://msdn.microsoft.com/en-us/library/xwth0h0d%28VS.80%29.aspx
Joe Daley
+1  A: 
Assert.IsTrue(default(MyClass) == null);
Bryan Watts
+1  A: 

You can decorate your properties with the DefaultValueAttribute.

private bool myVal=false;

[DefaultValue(false)]
 public bool MyProperty {
    get {
       return myVal;
    }
    set {
       myVal=value;
    }
 }

I know this doesn't answer your question, just wanted to add this as relevant information.

For more info see http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

Peter
+1  A: 

The default value for classes is null. For structures, the default value is the same as you get when you instantiate the default parameterless constructor of the structure (which can't be overriden by the way). The same rule is applied recursively to all the fields contained inside the class or structure.

Konamiman