Search code examples
c#inheritanceeiffel

Accessing Parents attributes


It might be a silly question, but i'm new to C#. I am wondering if there is a way to use directly parent's attributes in child class. I did a lot of Eiffel and when a class is inherited by one or more classes(cause yes Eiffel don't have interfaces you can inherit multiple classes).

Just like that exemple:(Eiffel langage)

Parent Class:

class Parent

features
    int id
    string lastName

Child Class:

class Child inherit

    PARENT

feature
    bool isChild

In that case, Child class already got access to id and lastName and can be set directly as part of Child attributes, don't have to create a Parent.

But so far i made this(C# langage):

Parent class:

public class Character
{
    Int32 Id;
    String name;
    List<String> images;

    public Character()
    {
        name = "";
        images = null;
    }

    public Character(string a_name, List<String> imagePaths)
    {
        name = a_name;
        images = imagePaths;
    }

    public Character(Int32 a_id, string a_name, List<String> imagePaths)
    {
        Id = a_id;
        name = a_name;
        images = imagePaths;
    }
}

Child class:

public class NPC : Character
{

    public bool isVender;

    public NPC()
    {
        Character character = new Character();
        isVender = false;
    }

    public NPC(string a_name, List<String> images)
    {
        Character caracter = new Character(a_name, images);
        isVender = false;
    }

    public NPC(string a_name, List<string> images, bool a_bool)
    {
        Character caracter = new Character(a_name, images);
        isVender = a_bool;
    }

}

So there is my question, is there a way to get acces directly to parent's attributes in C# just like Eiffel?


Solution

  • Declare the fields you want to use in child classes as protected. Learn more about protected visibility modifier here.

    public class Character
    {
        protected Int32 Id;
        protected String name;
        protected List<String> images;
    
        public Character()
        {
            name = "";
            images = null;
        }
    
        public Character(string a_name, List<String> imagePaths)
        {
            name = a_name;
            images = imagePaths;
        }
    
        public Character(Int32 a_id, string a_name, List<String> imagePaths)
        {
            Id = a_id;
            name = a_name;
            images = imagePaths;
        }
    }
    

    Then you can use the protected fields in child classes.