Search code examples
c#stringref

Creating a dynamic string in C#


I have string which I create like:

string label = Name + " " + Number;

where Name and Number are properties. I want this label string to change whenever the Name or Number is updated. I tried to use the ref keyword but C# tells me that I can't use ref for properties. Is there a way to achieve this ?


Solution

  • Create it as another property, with only a get method:

    public string Label { get { return Name + " " + Number; }}
    

    This way, every time you call the property it will create the return value based on the current values of Name and Number.

    This needs to be defined at a class level though, and Label is probably not an appropriate name either.


    Of course, the question now is, why call it Label in the first place?

    If you are using this value to set a WinForms style label control, and you want to update that dynamically then you will need a different approach. you could modify your current properties for Name and Number to do a "little extra work" in the setters.

    For example:

    private string _name
    public string Name 
    {
        get { return _name; }
        set { _name = value; DoChange(); }
    }
    
    private string _number
    public string Number 
    {
        get { return _number; }
        set { _number = value; DoChange(); }
    }
    
    public string Label { get { return Name + " " + Number; }}
    
    private void DoChange()
    {
        MyLabel.Text = Label;
    }
    

    This might be overkill for this question, but just something to think about.