开发者

Skipping fields on model classes

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


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜