Inheritance Part 2

G

Guest

I have a class (base) which has 1 field (_MyField) and 1 method
(DoSomething() ).

This class is inherited by another class (MyClass). This class sets
_MyField to a value and then invokes DoSomething. When Do Something is
invoked, _MyField is always null. Why?

public abstract base
{
protected string[] _MyField;
public base()
{
}
public string DoSomething()
{
return _MyField[0];
}
}

public class MyClass : base
{
private string[] _MyField = { "one", "Two", "Three" };
public MyClass()
{
Console.Writeline ( DoSomething() );
}

}
 
J

Jon Skeet [C# MVP]

JimHeavey said:
I have a class (base) which has 1 field (_MyField) and 1 method
(DoSomething() ).

This class is inherited by another class (MyClass). This class sets
_MyField to a value and then invokes DoSomething. When Do Something is
invoked, _MyField is always null. Why?

public abstract base
{
protected string[] _MyField;
public base()
{
}
public string DoSomething()
{
return _MyField[0];
}
}

public class MyClass : base
{
private string[] _MyField = { "one", "Two", "Three" };
public MyClass()
{
Console.Writeline ( DoSomething() );
}
}

You've got two _MyField variables - the one in the derived class hides
the one in the base class, but doesn't replace it. In other words, the
line of your description: "This class sets _MyField to a value and then
invokes DoSomething" is inaccurate.

Try this:

public class MyClass : base
{
public MyClass()
{
_MyField = new string[] { "one", "Two", "Three" };
Console.Writeline ( DoSomething() );
}
}

(Oh, and please try to not name your classes with C# keywords...)
 
B

Bjorn Abelli

JimHeavey said:
I have a class (base) which has 1 field (_MyField) and 1 method
(DoSomething() ).

This class is inherited by another class (MyClass). This class sets
_MyField to a value and then invokes DoSomething. When Do Something is
invoked, _MyField is always null. Why?

Because you *don't* populate the _MyField inherited from the base class, but
the array _MyField in MyClass, which is *hiding* the inherited field.

Simply don't redefine it, e.g.:

public class MyClass : base
{
public MyClass()
{
_MyField = { "one", "Two", "Three" };
Console.Writeline ( DoSomething() );
}
}


/// Bjorn A
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top