Rafael Herscovici
Rafael Herscovici

Reputation: 17104

Derived class - extending properties

i am still learning and fighting derived classes.

tried something simple ( from the examples i have seen all over ):

public class BaseClass
{
    public string Title {get;set;}
}

public class Channel : BaseClass
{
    public string Path { get; set; }
}


Channel myChannel = new Channel();
myChannel.Title = "hello";
myChannel.Path = "123";

but i get an error on the myChannel.Path line saying BaseClass does not contain a definition for Path and no extension....

help me please, what am i doing wrong?

Upvotes: 1

Views: 1424

Answers (3)

AlanT
AlanT

Reputation: 3663

The code as written runs fine. What I suspect you have is

BaseClass myChannel = new Channel()

If so, the problem is that myChannel is a reference to a BaseClass and cannot see the Path property.

If you need to access Path you can do so with

(myChannel as Channel).Path = "123";

hth,
Alan.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500675

The code you've given compiles fine. I suspect you've actually got code like this:

BaseClass myChannel = new Channel();
myChannel.Title = "hello";
myChannel.Path = "123";

Note that here, the compile-time type of myChannel is BaseClass - so the compiler wouldn't be able to find the Path property, as it's not present in BaseClass. The compiler can only find members based on the compile-time type of the variable. (Leaving dynamic typing aside...)

If you stick to the code you actually posted, i.e. with a compile-time type of Channel, then all should be fine.

Upvotes: 5

Marc Gravell
Marc Gravell

Reputation: 1062865

The example you show is fine. I think in your actual code you have:

BaseClass myChannel = new Channel();
myChannel.Title = "hello";
myChannel.Path = "123";

so the answer is simply: ensure your local variable is typed as Channel, since it is the the expression type (typically: the type of a variable) that determines the starting point for member resolution.

As a terse alternative in C# 3:

var myChannel = new Channel { Title = "hello", Path = "123" };

Upvotes: 5

Related Questions