Search code examples
c#automatic-properties

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


Solution

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