views:

127

answers:

3

Hello there! I have this set of classes:
Node (SUPER Class)
|------ NodeType1 (Class)
|----------NodeType2 (Class)

There are fields that the type1 and type2 have in common (For example: NAME). If i declare the NAME field in the SUPER class (Node) how should I access those variables in the types classes? How can i make those property's? Thank you for your time

+3  A: 
class Node
{
    public string Name { get; set; }
}

class NodeType1 : Node
{
    void SomeMethod()
    {
        string nm = base.Name;
    }
}

class NodeType2 : NodeType1
{
    void AnotherMethod()
    {
        string nm = base.Name;
    }
}
Aviad P.
Actually, you don't even need the "base." in front of the property
Rik
You haven't understood my question, but i see what you mean. you have helped.
Ricardo
@Rik, Not in this case, but in the general case, where there might be a property with the same name hiding the base one, you do.
Aviad P.
+1  A: 

You can access this field just the way you usually get access to the field, typing this.fieldName, for instance. Don't forget to mark this field as protected to be visible in inheritors or public to be visible both in inheritors and from outside the class.

class Node
{
    protected string protectedName;
}

class NodeType1 : Node
{
    public string Name
    {
        get
        {
            return protectedName;
        }
    }
}

class NodeType2 : NodeType1
{
    protected void Foo()
    {
        string bar = Name;
    }
}
Li0liQ
thank you for your help
Ricardo
+2  A: 

If the access modifier of the name field is public or protected you will be able to access it in your derived classes. The modifier public will make it visible to all other classes, while protected will restrict visibility to the derived classes.

In either case you can just access it as you would a field declared in the current class:

this._name = "New Name";

If you wish to make it a property then set it's access modifier accordingly:

public class Node
{
     protected string Name { get; set; }
}
ChrisF
So, if the fields are 'protected' the NodeType's will access then by this.Field. And then inside the Type i make those fields property?
Ricardo
public class Node{ protected string Name { get; set; }}I tried this once, and I must have crewed up...It didnt become a property
Ricardo
@Ricardo - Yes to your first question (I was updating my answer as you commented). The point about the property was to say that the same rules apply to properties as the do to fields. I don't know why the code you have didn't work. You'd need to post your usage and the error message.
ChrisF
No need, you have answered my question. thank you
Ricardo