Newbie question -- passing strings to properties?

  • Thread starter Thread starter Richard Brown
  • Start date Start date
R

Richard Brown

I have the following two classes...

public class classA {
private string text;

public string Text {
get { return text; }
set { MessageBox.Show(Text);
text = Text;
MessageBox.Show(Text);
}
}
}

public class classB {

void DoTest() {
classA varA;

varA = new classA();
MessageBox.Show(varA.Text);
varA.Text = "New Text";
MessageBox.Show(varA.Text);
}
}

When I call classB.DoTest, I get four blank message boxes! I can understand
the first one, with varA not being set yet, but the last three should all
have "New Text"! It seems that the string is not even getting 'inside' the
property set block.
 
Hello, have you tried this in debug mode? Stepping through the code, I see
that you are unaware of the use of the "value" keyword.

The line:

text = Text;

calls the get of the same property (Text), which has never been set, because
what you need instead of that line is:

text = value;

But don't feel bad for not knowing this: my "tech lead" made the same
mistake for several properties in a class, then told us all to use that
class because it was "done". BTW, I hate when people say some piece of code
is "done". (Am I the only one with that wierd pet peeve?)

-KJ
 
Back
Top