Default value for user defined class in C#

Viewed 89533

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?

10 Answers

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.

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

Assert.IsTrue(default(MyClass) == null);

For reference types or nullable value types the default will be null:

Person person = default; // = null
IEnumerable<Person> people = default; // = null
int? value = default; // = null

For value types, it depends on which value type it is:

int value = default; // = 0
DateTime dateTime = default; // = 1/1/0001 12:00:00 AM
Guid id = default; // = 00000000-0000-0000-0000-000000000000

Saving some other ppl's time, hopefully.

Obvious option nowadays (for which I still had to google a bit, as landed on this topic first) is to write an extention, that helps you to initialize a class, regardless of it's own complications (like constructor getters/setters, which prevent simple default value direct assignition).

Modifying previous answer a bit:

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 class Person 
{
    public string Name { get; set; }
    public string Address { get; set; }
}
public static class PersonExtentions
{
    public static Person withDefaults(this Person obj) {
      obj.Name = "John Doe";
      return obj;
    }
}

And then

Person x = new Person.withDefaults();
Related