views:

201

answers:

6

I've been programming for so long its hard to keep up with language changes sometimes...

Is it really ok to set properties like this after .net v2

    public string LocaleName
    {
        get;
        set;
    }

Not requiring an inner field? Seems like the compiler takes care of this lately?

+10  A: 

Yes, this is a new feature in C# 3.0

Pavel Minaev
So I amn programming in C# v3, but using the .net v2 framework?
JL
@JL, yes, it's a *C#* feature that doesn't require any specific framework version. :)
280Z28
It's more of a compiler feature with Visual Studio 2008. If you're using VS2005 with .NET 3.0 extensions, you would not get this feature.
Will Eddins
@280Z28 A C# feature may or may not need CLR support e.g. LINQ to 'X' does need CLR support whereas auto implemented properties don't because they are purely a compiler trick.
SolutionYogi
This feature requires the C# 3 compiler.
Andrew Hare
Cool, thanks Andrew - good point, its all about how it gets compiled
JL
@solutionYogi LINQ does require the same version of the CLR as auto properties (v2) it's syntactic sugar in both cases. There was no change to the CLR going from c#v2 to C#v3
Rune FS
The term for this is syntactic sugar - the compiler is just making the syntax easier but the generated IL is actually still using an inner field.
Robert MacLean
+3  A: 

It's fine as long as you don't need to do any checking to see if the values are set the right way.

You might take a look at the C# Specification.

Lucas McCoy
+1  A: 

Yes, these are called 'auto implemented properties'. Compiler will create a backing field for your property.

Because 'auto implemented properties' are 'C# compiler trick', you can use them in your code and target .NET framework 2.0, as long as you use C# 3.0 compiler to compile your code.

SolutionYogi
A: 

Yes, they're called automatic properties, and will generate the backing field behind the scenes.

Chris Doggett
A: 

Yes. In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field can only be accessed through the property's get and set accessors.

+3  A: 

Just so you know, you can also do something like this:

public string MyString
{
   get;
   private set;
}

which gives you a public accessor but a private setter.

Sterno