Jump to content

C# class property auto implementation confusion (simple explanation)

kaddle

i'm confused about the getset property auto implementation. i understand how the property itself works.

 

    class One
    {
        private int number = 50;
        public int Number
        {
            get
            {
                return number;
            }
            set
            {
                if (value >= 0)
                    number = value;
                else
                    number = 0;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var one1 = new One();
            one1.Number = -90;

            Console.WriteLine(one1.Number);
            Console.ReadLine();
        }
    }

the getter allows other classes to read the value of the field. the setter allows other classes to set the value of the backing field. if the getter is private then other classes can't read the field. if the setter is private then other classes can't set the value of the backing field.

 

this is where the concept of auto implemented getset property gets confusing.

the book says that when you use the shorthand to create an auto implemented property, it creates an anonymous private backing field. so how are you supposed to know what the backing field is? i thought that the whole point of using the property was to give limited access to the field from other classes in order to protect the field. are there situations when i won't need to know what the backing field is?

 

also, if using the shorthand allows full access to reading and changing the value of the backing field (aside from making the getter or setter private), is there any point to using it?

Link to comment
Share on other sites

Link to post
Share on other sites

A lot of the time, properties are simply used to access fields. They have no extra logic in them. If that's  the case, you can use shorthand notation. If you need some additional logic later on, you can replace the shorthand notation with a custom implementation.

 

The owning class itself would simply use the property as well. There's no need to "know" the backing field, unless you need direct access for some reason. If that's the case shorthand isn't an option.

 

As long as classes only ever use the property, you don't have to refactor them when change the internal implementation. From the outside, the property hasn't changed, even if its internal implementation changes.

 

tl;dr: Short hand allows you to write less code, while maintaining proper encapsulation so you can change the internal implementation when needed, without breaking the public interface of your class.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

Autoproperty might be complex to understand but it's not. If you are doing metrics, you cannot measure a field accessibility. What i mean by that you can't know how many time the field has been read or set while a property you can.This is only a portion of what they are useful at. Property also have its own type when using reflection so you can differentiate between them even though in the end you have a field somewhere. The property allow you to control the getter and setter state, one can be private the other one public without problem. Using a field you cannot do that. You need to create the getter method and setter method separately with their own state (which is what the compile does for you with auto property anyway)

 

public class test
{
    public double SomeData { get; set; } = 0d;
}

// the above compiled will assume public gettter and setter and will be the exact same as if you wrote down this instead :

public class test
{
    private double _someData = 0d;
    public double SomeData { get { return _someData; } set { _someData = value; } };
}

// no matter what you do, as long has you have a "get" and/or "set" it will compile to 
// 1 field and 1 or 2 methods like you have to do in C++ so it's compiled to exactly what you see below

public class test
{
    private double _someData = 0d;
    public double GetSomeData()
    {
        return _someData;
    }
    public void SetSomeData(double someData)
    {
        _someData = someData;
    }   
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

On 11/2/2019 at 7:56 PM, kaddle said:

also, if using the shorthand allows full access to reading and changing the value of the backing field (aside from making the getter or setter private), is there any point to using it?

If you use an auto-property (and you should always if it's a publicly accessible item) then you should never have to touch the backing field. It's why the auto-property backing fields are "anonymous" so you aren't tempted to use them.

Link to comment
Share on other sites

Link to post
Share on other sites

Actually, the shorthand:

 

public string Name { get; set; }

 

(rightly) prevents you from accessing the backing fields.

 

You would use the longhand version if you wanted to enforce validation or set values in other properties.

 

A good example of how this is commonly used is for serialization.

 

If you have a date value that is coming in from a data source via serialization (i.e., Xml or JSON), you can capture the string value from the serialization and do the type conversion in the object on the fly in another property, like so:

private string _receivedOn;

[XmlIgnore]
public DateTime? ReceivedOn
{
    get => DateTime.TryParse(_receivedOn, out DateTime dt) ? dt : (DateTime?)null;
}


[XmlAttribute("ReceivedOn")]
public string ReceivedOnVal
{
    get => _receivedOn;
    set => _receivedOn = value;
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×