开发者

Default value for user defined class in C#

开发者 https://www.devze.com 2022-12-14 18:03 出处:网络
I see some code will return the default value, so I am wondering for a user defined class, how will the c开发者_如何转开发ompiler define its default value?To chime in with the rest, it will be null, b

I see some code will return the default value, so I am wondering for a user defined class, how will the c开发者_如何转开发ompiler define its default value?


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 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.


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

精彩评论

暂无评论...
验证码 换一张
取 消