Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Inheritance question

Tags:

c#

inheritance

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)?

like image 301
JL. Avatar asked Sep 08 '09 09:09

JL.


2 Answers

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") {}
}
like image 50
Marc Gravell Avatar answered Oct 01 '22 13:10

Marc Gravell


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.

like image 45
Jon Skeet Avatar answered Oct 01 '22 13:10

Jon Skeet