Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do C# automatic properties not support default values like VB 2010?

Looking at the new VB 2010 features, I stumbled upon support for Auto-Implemented Properties.

Since I'm working with C#, this seemed quite familiar, but I noticed that VB did add a feature I would love to have in C#: setting an arbitrary default value for the auto-implemented property:

Public Class Person

    Property Name As String = "Scott Guthrie"
    Property Age as Integer = 35

End Class

I really like the clean usage of auto-properties in C#. This would save us the effort of introducing a backing field and hooking it up to the property every time we simply need a default value, thereby cluttering up the code unnecessarily.

I was wondering why this wasn't introduced in C# as well? What could be the rationale for not doing this? Is a syntax discussion going on, or are there technical limitations to implementing this?

like image 921
Rob van Groenewoud Avatar asked Apr 13 '10 08:04

Rob van Groenewoud


2 Answers

Why not just default them in the constructor? That's what its for too.

like image 144
Preet Sangha Avatar answered Nov 02 '22 16:11

Preet Sangha


What about:

public class Person
{
    public Person() 
    {
         this.Name = "Scott Guthrie";
         this.Age = 35;
    }
    public string Name { get; set; }
    public string Age { get; set; }
}

in practice, that comes down to the same and isn't that much extra work, I believe. But perhaps, for once in a long while, VB looks clearer then C#... ;-)

EDIT (rationale):
You were asking for the rationale in your last comment under (and in) your original question. Thinking out loud, I think that the principle in C# that initialization code goes to one place and one place only, namely the constructor, is the reason for this decision. Adding another place where you have to look to find initialization code makes debugging harder and the code less clear.

Obviously, an inline initialization value cannot contain other initializations or calculations (at least, very limited). While I agree that it can be more concise in the VB way, I would understand the C# team and Anders Hejlsberg if they said that they consider it a bigger advantage to have one place for initialization.

EDIT: here's what Microsoft says about it. In short, not for C# 4.0, but perhaps C# 5.0? Also:

"It is not as easy as it sounds though: the next thing you want is for the constructor to initialize the backing field, but it can only do that through the setter, which might not be what you want."

and (just a commenter):

"Lack of initialization or constructor control makes the feature practically worthless for properties returning a reference type."

like image 22
Abel Avatar answered Nov 02 '22 17:11

Abel