Reputation: 1
I have a "simple" problem, and I crated an example app to illustrate. I would like the b.getName()
call to return "barname", but it does not, and I'm not sure how to get this to work. I've been working in C# for years, but at the moment I feel like a newbie because this late binding problem has me stumped.
class Program
{
static void Main(string[] args)
{
bar b = new bar();
Console.WriteLine(b.getName());
Console.ReadLine();
}
}
class foo
{
string name = "fooname";
public string getName()
{
return this.name;
}
}
class bar:foo
{
string name = "barname";
}
Upvotes: 0
Views: 416
Reputation: 19599
This isn't related to late binding. Late binding generally refers to calling a method at runtime from the name.
What your supplied code actually does is create a new variable that's in a different scope than what your base class has access to.
In order to get the desired effect, you actually need to either 1) make the base class method implementation virtual, and override the method in your child, or 2) in your base class change your variable to have a default accessibility of protected
and set the value in your derived class's constructor(s).
Upvotes: 2
Reputation: 38758
If you're not married to having a private class variable, you can accomplish this with an overridden property:
class foo
{
public virtual string Name
{
get
{
return "fooname";
}
}
}
class bar : foo
{
public override string Name
{
get
{
return "barname";
}
}
}
Upvotes: 3
Reputation: 160852
By default your name
variable is private - it sounds like you want it to be protected
, so you can overwrite the value - this would work:
class foo
{
protected string name = "fooname";
public string getName()
{
return this.name;
}
}
class bar : foo
{
public bar()
{
name = "barname";
}
}
Upvotes: 5