98

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?

3
  • 4
    Just to clarify: all classes (including the ones you create) will default to null. Number value types will default to zero and structs are implementation defined (values are set in the constructor). Commented Dec 17, 2009 at 7:57
  • 4
    Actually, structs have an implicit default constructor that can't be overriden which zero's out the memory used by the struct, so the default value is still compiler defined, not implementation defined. Commented Dec 17, 2009 at 8:03
  • 2
    Important distinction: Class members are initialized with their default value. Uninitialised local function variables just give compiler errors ;) Commented Jun 28, 2016 at 11:03

10 Answers 10

107

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 There is a full explanation of the default keyword at msdn.microsoft.com/en-us/library/xwth0h0d%28VS.80%29.aspx
23

The default value for class is a null

Comments

22

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

1 Comment

As the page says, DefaultValue is just something used by the visual designer of VS. It's really completely unrelated to actual initialization; it's just a "hint" of how it should be initialized.
12

If you are wondering why there isn't a language feature that allows you to somehow define a non-null default value for a class, remember that a class is a "reference type". A reference type is a reference to allocated memory, or in other words, anything except null is a constructed instance of that object which required memory to be allocated. So now thinking about how to integrate the "default" keyword into .NET so that it works for classes, imagine two implementations that could be considered:

  1. You can define a static instance that is marked as the default. Maybe "default" becomes like an access modifier (e.g. public default readonly etc). This could work, maybe. But is it really a worthy language feature? At least this way every "default" would point to the same static instance of memory.

  2. What if the default constructor were called every time you used the default keyword on a class? This would be terrible because two default values could possibly be unequal to each other if you didn't override Equals to not compare references, and also terrible because of the memory management and memory allocation performance hit, and side affects from the constructor.

So in summary I think it is a language feature that we really don't want. And default(MyClass) will always == null.

1 Comment

Great explanation. I sort of got the impression that default was just meant to be an alternative to null when the IDE suggested to replace null for a generic <T> with default(T) instead.
11

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
}

Comments

10

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.

Comments

5

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

Comments

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

1 Comment

what is the purpose of this assert?
2

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

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.