Search code examples
c#propertiesprivateencapsulation

C# Automatic properties to wrap private fields?


Can I encapsulate a private field through an automatic property in C#? When i use C# properties i surely can encapsulate private fields like.

private string owner;
public string Owner
{
  get { return owner; }
  set { owner=value;}
}

What happens when i use an automatic property?

public string Owner { get; set; }

That way I only interact with the property itself, right? Is there any way to use an automatic property to encapsulate a private field? How does it work?


Solution

  • Is there any way to use an automatic property to encapsulate a private field?

    Yes; that is exactly what an automatically implemented property is. Simply: the compiler declares the field for you - you never see the field directly. Perhaps the real question here should be:

    If I use an automatically implemented property, can I access the underlying field directly?

    To which the answer is: no; just access the property instead. After JIT inlining, you'll never know the difference anyway.