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?
If it is a reference type, the default value will be null
, if it is a value type, then it depends.
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.
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
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.