1

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 ?

1
  • 3
    Why can't you just update the string in your Name and Number property setters? Commented Feb 19, 2013 at 10:33

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You could implement a Label property, inside the class that provides Name and Number, like so:

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

Comments

2

Even being a reference type a string behaves like a value type, so every time you assign to it something it keeps a new copy of the value.

But even if it wouldn't behave like that, this will not resolve your problem, as your label value is compositional value, based on other 2 values.

You need to architect your code in a way, that when:

(just an example) one of the properties is changed (Name or Number), event raised, so label recomputes its value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.