Best way to update a class when modifying a member

Hi,

I have a UserControl derived class containing a Label, which I would like to be updated every time a public string on the class is modified. For this, I created accessors for the public string, in this way:

public class MyControl : UserControl {
private Label _label;
private string _string;

public string MyString {
get {return _string; }
set {_string = value;
_label.Text = value + " " + value; /* do something fancy with the new value */}
}

/* ... */
}

What I dislike of this approach is that I have the feeling of having duplicated the string inside my class. I am not sure if this is accurate, as I am new to C# development. Anyway, is there any other way to update elements of a class when a member is modified Could you advice me in the sense of best practices in C#

Thanks,

Claudio


Answer this question

Best way to update a class when modifying a member

  • shafiqm

    Hi

    then the original code you proposed would really be the best approach.

    In .net strings are immutable, so yes on the one hand you are duplicating the string

    on the other hand, you need the original cased value...

    Hope this helps you out, please close the thread if it does



  • AlexBB

    There is nothing wrong with your original code.

    Strings are immutable - meaning that they cannot be modified. When you do modify a string you are in fact creating a new string.

    So your code is correct.



  • rob_a89

    Hi Frederik,

    Thanks for your reply. The problem with your approach is that I don't want to display exactly the same string that is set. Say, I'd like to display it all caps, but when getting it, I'd like to get the original capitalization. Then, for instance:

    myClass.MyString = "This is Not All Caps"; /* this would display "THIS IS NOT ALL CAPS" */

    string s = myClass.MyString /* s == "THIS IS NOT ALL CAPS", which is not the string I set. */

    I hope to be clear enough in why just setting and getting to the :Text property of the Label is not ok.

  • mehdi61e

    Hi

    one other way to do it would be, without having the duplicate string :)

    private Label _label;

    public String Text{

    get{return _label.Text;}

    set{_label.Text = value; //go all fancy with your value}

    }

    Otherwise, if your label uses a string property of an object, consider databinding :)

    Hope this helps you out, please close the thread if it does



  • Best way to update a class when modifying a member