Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning about Auto-Implemented Properties

I have the simple class using auto-implemented properies:

Public Class foo
{
    public foo() { }  

    public string BarName {get; set;}
}

I obviously use the variable BarName throughout my class and now need to add logic when the property value is set (it must be all upper case, go figure). Does this mean that I need to now create a private variable for BarName , e.g. _BarName, and change the current BarName variable used throughout my class to _BarName?

Public Class foo
{
    public foo() {}  

    private string _BarName = "";
    public string BarName 
    { 
        get {return _BarName;}
        set {_BarName = Value.ToString().ToUpper();}
    }
}

I am trying to make sure I understand the implications of using auto-implemented properties, and what it will entail down the road when/if I need to change something. I am assuming that the refactoring, as shown above, is not a breaking change because the property is basically staying the same; it just took a little work inside the class to keep it that way and add the needed logic.

Another example, which may be more meaningful is that I need to call some method when a setter or getter is used; more then changing the value.

This seems a fair trade off the the lines and lines of code to setup properties.

like image 507
Brettski Avatar asked Dec 02 '22 08:12

Brettski


1 Answers

Does this mean that I need to now create a private variable for BarName

Yes

and change the current BarName variable used throughout my class

Do not change the rest of the code in your class to use the new private variable you create. BarName, as a property, is intended to hide the private variable (among other things), for the purpose of avoiding the sweeping changes you contemplate to the rest of your code.

I am assuming that the refactoring, as shown above, is not a breaking change because the property is basically staying the same; it just took a little work to keep it that way and add the needed logic.

Correct.

like image 127
hurst Avatar answered Dec 03 '22 22:12

hurst