JL.
JL.

Reputation: 81262

C# Inheritance question

I have a class that has private fields... (cars)

I then inherit from this class... (Audi)

In the (Audi) class, when I type this. in the constructor...

the private fields are not available...

Do I need to do anything special to expose this private fields in (cars) class so that they are accessible via this. in (Audi class)?

Upvotes: 6

Views: 788

Answers (4)

Marc Wittke
Marc Wittke

Reputation: 3154

You are probably looking for a concept called constructor inheritance. You can forward arguments to the base classes constructor - see this example, where the Audi has a flag indicating whether it's an S-Line edition or not:

namespace ConstructorInheritance
{
    abstract class Car
    {
        private int horsePower;
        private int maximumSpeed;

        public Car(int horsePower, int maximumSpeed)
        {
            this.horsePower = horsePower;
            this.maximumSpeed = maximumSpeed;
        }
    }

    class Audi : Car
    {
        private bool isSLineEdition = false;

        // note, how the base constructor is called _and_ the S-Line variable is set in Audi's constructor!
        public Audi(bool isSLineEdition, int horsePower, int maximumSpeed)
            : base(horsePower, maximumSpeed)
        {
            this.isSLineEdition = isSLineEdition;
        }
    }

    class Program
{
    static void Main(string[] args)
    {
        Car car = new Audi(true, 210, 255);
        // break here and watch the car instance in the debugger...
    }
}    }

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499830

Philippe's suggestion to declare the fields as protected instead of private will indeed work - but I suggest you don't do it anyway.

Why should a derived class care about an implementation detail of how the data is stored? I suggest you expose protected properties which are (currently) backed by those fields, instead of exposing the fields themselves.

I treat the API you expose to derived classes as very similar to the API you expose to other types - it should be a higher level of abstraction than implementation details which you may want to change later.

Upvotes: 17

Marc Gravell
Marc Gravell

Reputation: 1062494

One (bad) option is to make the fields protected - but don't do this; it still breaks proper encapsulation. Two good options:

  • make the setter protected
  • provide a constructor that accepts the values

examples:

public string Name { get; protected set; }

(C# 2.0)

private string name;
public string Name {
    get { return name; }
    protected set { name = value; }
}

or:

class BaseType {
  private string name;
  public BaseType(string name) {
    this.name = name;
  }
}
class DerivedType : BaseType {
  public DerivedType() : base("Foo") {}
}

Upvotes: 20

Philippe Leybaert
Philippe Leybaert

Reputation: 171734

You should declare them as "protected" instead of private

Upvotes: 11

Related Questions