Let’s say I have a class with a public property used for property injection, like this:
public partial class ManageFoo : PageBase
{
[Inject]
public IFoo Foo { get; set; }
public void SomeMethod()
{
this.Foo.Bar();
}
}
Our IoC container handles injecting an instance of IFoo into the property. As you can see the property Foo uses the short hand { get; set; } to define the property. However I have heard it is bad practice to use the public property throughout the class and I should have an accompanying private variable like this:
public partial class ManageFoo : PageBase
{
[Inject]
public IFoo Foo
{
get { return _foo; }
set { _foo = value; }
}
private IFoo _foo;
public void SomeMethod()
{
_foo.Bar();
}
}
I’ve heard differing opinions but I’ve yet to hear some concrete reasons why one is better than another. Is the shorter syntax preferred or is the private variable preferred, and why?
There’s no significant difference between using an automatically-implemented property and using the explicit form. Yes, your class’s code will all go through the property – which is almost certainly going to be inlined by the JIT.
The automatically implemented property gives you less code, and it’s clearer – go for it. Next time someone tells you it’s bad practice to refer to a public property within the class that declares it, ask for concrete examples of how it can be harmful 🙂