views:

41

answers:

2

Hello stackoverflow,

Recently, after reading a lot of tutorials around the Internet, I've noticed that some developers skips writing the fields in their model classes and just go with properties, like this:

public class MyClass
{
    public string MyProperty { get; private set; }
}

What exactly is the benefit of doing this, apart from writing less code that is? While I do realize that the setter is private, isn't there some kind of security issues when you don't specify your private fields? In other words: what's the best practice here? Writing model classes without fields and related properties, or just go with these public properties without the fields?

Thanks in advance,

Bo

+5  A: 

In c# 3.0 and above, the compiler will put the local variables into the MSIL for you. It makes the code easier to read and more maintainable (less variables to keep track of, etc).

There should be no security issue because internally it is creating locally scoped member variables.

See Microsoft's documentation for more info.

Bob
Perfectly, Thanks a lot Bob. That MS Doc link was just what I was looking for :) currently writing a report/review where I needed the source to document this.
bomortensen
+1  A: 

If you are not doing any operations on the variables, just setting them and reading them, as they are, then why add the extra code to create a private variable and do the complete setter and getter?

C# will create the private variable so the byte-code is still correct, but for anyone reading your program there it is easier to understand what is going on.

Any time you can make code easier to read, even if there is syntactic sugar in the compiler, it is a win.

But, if you have to do any operation, such as check that the property is within a certain range, then, in C#3 you still need to write everything else out yourself.

The best practice is to just write it as you have in the question.

James Black