I see some code will return the default value, so I am wondering for a user defined class, how will the compiler define its default value?
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables aren't given a default value. You can declare but not use an uninitialised local variable. In Java, the default value of any object is null.
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).
You can simply provide a default value by writing an initializer after its declaration in the class definition. Both braced and equal initializers are allowed – they are therefore calle brace-or-equal-initializer by the C++ standard: class X { int i = 4; int j {5}; };
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.
The default value for class
is a null
Note: A DefaultValueAttribute
will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
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.
I would make this "default" class instance a field rather than property, like how System.String.Empty
looks:
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public static readonly Person Default = new Person()
{
Name = "Some Name",
Address = "Some Address"
};
}
...
public static void Main(string[] args)
{
string address = String.Empty;
Person person = Person.Default;
//the rest of your code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With