Setting a read-only object from a derived class - c#

I am writing a library that other developers in our company will use. A state machine base class has a ReadOnlyCollection<T> of allowed states, etc. Developers need to inherit from this class and set the allowed states.
I want to limit them to initialize the ReadOnlyCollection<T> in the constructor of their derived classes and not be able to modify it later.
If I declare the ReadOnlyCollection<T> as a read-only property in the base class, that does not work since it cannot be modified in the constructor of the derived class.
I imagine this to be a not-so-uncommon scenario. Any elegant way to achieve this short of having developers override the ReadOnlyCollection<T>?

Don't let them initialize by themselves. Make your base class constructor to take the collection as an argument:
public class BaseClass
{
protected readonly Collection someObject;
public BaseClass(Collection object)
{
someObject = object
}
}
So now when the derived class constructor is called it should call base class constructor also with the collection object
otherwise it will be a compile time error. This will make sure that the collection is initialized in the constructor and no where else.
public class Derivedclass : BaseClass
{
public DerivedClass() : base(/*pass the collection object here*/)
{
}
}
Still there is a pit fall in this, if you get the reference of a collection, you can still modify the collection by calling Add or remove method of the collection in the derived class only thing is you cant reinitialize if its readonly.

Does it have to be a ReadOnlyCollection ?
I would go for IEnumerable.
This could be done like this, similar to srsyogesh´s answer:
public abstract class StateMachine
{
public StateMachine(params States[] allowedStates)
{
_allowedStates = allowedStates;
}
private readonly IEnumerable<States> _allowedStates;
public IEnumerable<States> AllowedStates
{
get { return _allowedStates; }
}
}
public class DerivedStateMachine : StateMachine
{
public DerivedStateMachine()
: base(States.State1, States.State2)
{
}
}
Of course, one could still cast the Property back to an array and change it, but that would be kind of criminal. Depends on your audience. To be more bullet proof, you could, instead of just returning the field, iterate over the contents:
public IEnumerable<States> AllowedStates
{
get
{
foreach(var state in _allowedStates)
yield return state;
}
}

Related

Accessing protected constructor from derived class instance

G'day Folks,
I'm struggling with what I thought was a simple issue, but I've gone blind. Obviously, I'm doing something basic very wrong, but I can't see it.
What I'm trying to do: Create an instance of a base class from a derived class instance using a protected constructor.
What's happening: The protected constructor of the base class is inaccessible inside the derived class. Message: 'BaseClass.BaseClass(List)' is inaccessible due to its protection level
Consider the following code:
class BaseClass
{
protected readonly List<int> internalStuff;
// Normal constructor for everywhere else
public BaseClass()
{
internalStuff = new List<int>();
}
// this is the constructor I want to call; it shouldn't be accessible outside the derived classes hence protected
protected BaseClass( List<int> stuff )
{
internalStuff = new List<int>(stuff);
}
}
sealed class DerivedClass : BaseClass
{
public void ConvertToBaseClass( out BaseClass newBaseClassInstance )
{
newBaseClassInstance = new BaseClass(internalStuff);
}
}
The protected constructor should be visible to the derived class, right? Why is it inaccessible?
Edited to answer some questions. The code you see is the code that exists. I created the classes in a separate file and trimmed as much as sensible.
The reason I want to convert between the classes is the base class is "light" in that it contains no unmanaged code nor holds on resources. The derived class holds resources. When I am done with the derived class, but need to maintain the basic data, I want to convert to the base class.
Here is revised code to answer some of the comments below:
public class BaseClass
{
protected readonly List<int> internalStuff;
public BaseClass()
{
internalStuff = new List<int>();
}
protected BaseClass( List<int> stuff )
{
internalStuff = new List<int>(stuff);
}
}
sealed class DerivedClass : BaseClass
{
BaseClass bc;
public void ConvertToBaseClass( out BaseClass newBaseClassInstance )
{
bc = new BaseClass(internalStuff); // <- error
newBaseClassInstance = new BaseClass(internalStuff); // <- error
}
}
Public on BaseClass did nothing, nor did I expect it to. Both BaseClass and DerivedClass are in the same assembly and namespace so are visible to each other anyway.
Even if there is a BaseClass variable internal to derived class, it gives the same inaccessible error.
DerivedClass is a derived class, go figure. Why does it not have access?
There are two flaws to your request:
the instance of DerivedClass already IS and instance of the BaseClass so there is no need to convert it!
Your DerivedClass has not implemented the constructor overload with stuff parameter so there is no way for this class to access that constructor.
If the constructor is protected, then it can only be accessed via constructors in inherting classes or the base class itself, Normally we would use syntax like this when implementing a class and we want the specific base constructor to be called, but we only want internal logic to access it:
public sealed class DerivedClass : BaseClass
{
public DerivedClass ()
: base()
{
// the base implementation has been executed.
// now perform any other init logic you need.
}
private DerivedClass (List<int> stuff)
: base(stuff)
{
// the base implementation has been executed.
// now perform any other init logic you need.
}
// this is one way to access non-public constructors
public static DerivedClass CreateAnotherInstance(List<int> stuff)
{
return = new DerivedClass(stuff);
}
}
What you may not be aware of, and the reason that you don't need a Convert method at all is that and instance of DerivedClass IS an instance of BaseClass, the following statement is valid:
DerivedClass car = new DerivedClass();
BaseClass vehicle = car;
The following will also work if you are unsure if the base object was originally a specific derived implementation:
if (vehicle is DerivedClass derivedRef)
{
Console.Out.WriteLine("It was a DerivedClass instance all along");
}
else
{
Console.Out.WriteLine("Not a DerivedClass: " + vehicle.GetType().Name);
}
If your DerivedClass instance convert method returned a new instance of BaseClass then you would have to copy across all the neccessary properties and would lose the polymorphic abilities that Inheritance provides for our classes.
In regard to your update:
The reason I want to convert between the classes is the base class is "light" in that it contains no unmanaged code nor holds on resources. The derived class holds resources. When I am done with the derived class, but need to maintain the basic data, I want to convert to the base class.
I really can't understand why you would, that's not true, I understand your reasoning, I just don't think it is a good design, even to the point that i feel very strongly against providing an answer that will help you continue down this path... this type of pattern really doesn't need to use inheritance at all... with extreme caution, as in please do not do this:
public class BaseClass
{
protected readonly List<int> internalStuff;
public BaseClass()
{
internalStuff = new List<int>();
}
protected BaseClass(List<int> stuff)
{
internalStuff = new List<int>(stuff);
}
protected BaseClass CreateAsBase()
{
return new BaseClass(internalStuff);
}
// I see little point in allowing "stuff" to be passed through
// from the caller, this class already has access to the "stuff"
// but you've already demonstrated an unual taste for hard work
protected BaseClass CreateAsBase2(List<int> stuff)
{
return new BaseClass(stuff);
}
}
sealed class DerivedClass : BaseClass
{
public BaseClass ConvertToBaseClass()
{
return base.CreateAsBase();
...
// um, if you really need to, this is how you could pass the "stuff"
// I asusme you would only do this because you were going to modify
// it in a way that the base class could not anticipate.
return base.CreateAsBase2(aModifiedListOfInternalStuff);
}
}
Usually in cases like this, either there would be a Utility class or methods to handle the processing and intensive resource requirements, and you would pass around a reference to the DTO (Data Transfer Object) so you can discard the wrapper object, but the DTO would remain intact:
public class Vehicle
{
protected readonly List<int> internalStuff;
public Vehicle()
{
internalStuff = new List<int>();
}
protected Vehicle(List<int> stuff)
{
internalStuff = new List<int>(stuff);
}
public Color Color { get; set; }
}
public sealed class Car : Vehicle
{
public Car()
: base()
{
}
private Car(List<int> stuff)
: base(stuff)
{
}
public void AddOne()
{
internalStuff.Add(1);
}
}
// Wrapper that accepts a vehicle, and does "stuff" to it
public sealed class VehicleBusinessObjectWrapper : IDisposable
{
public Vehicle Vehicle { get; private set; }
public VehicleBusinessObjectWrapper(Vehicle dto)
{
Vehicle = dto;
}
public void ChangeColour(Color newColor)
{
Vehicle.Color = newColor;
/// you know, apply modifications to the Vehicle
}
public void Dispose()
{
// clean up your resources... if there are any
// for instance, deliberately clear the reference to the original DTO, just to prove a point
Vehicle = null;
// after this point, the Vehicle Object is still intact.
}
}
public static class BusinessLogic
{
public static void Test()
{
var originalCar = new Car();
using (var processor = new VehicleBusinessObjectWrapper(originalCar))
{
// We can still access the vehicle through the processor, we don't need inheritance
if (processor.Vehicle.Color != Color.Green)
processor.ChangeColour(Color.Green);
// do other stuff on the car, or on the vehicle...
if (processor.Vehicle is Car car)
{
car.AddOne();
}
}
// reference to wrapper is now gone, but our original car/vehicle still remains.
originalCar.ToString();
Vehicle v = originalCar;
Console.WriteLine(v == originalCar); // "True"
}
}
This is by design. protected members of the base class can only be accessed on a object reference of your own type. So new BaseClass(internalStuff) is invalid. But creating your own constructor that calls through to it would be valid:
DerivedClass(List<int> stuff) : base(stuff) {
Let's look at the specifications:
ECMA-335 specification, which defines the CLI on which C# is based, says as follows:
I.8.5.3.2 Accessibility of members and nested types
snip
family [this means protected in C#] – accessible to referents that support the same type (i.e., an exact type and all of the types that inherit from it). For verifiable code (see §I.8.8), there is an additional requirement that can require a runtime check: the reference shall be made through an item whose exact type supports the exact type of the referent. [my bold] That is, the item whose member is being accessed shall inherit from the type performing the access.
ECMA-334, which defines the C# language, says:
8.5.4 Protected access
When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access shall take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class. [my bold]
So this restriction stops you from creating an instance of the base class, or indeed another derived class altogether, and calling protected base functions on it.
The constructor is no exception. You must have an instance of DerivedClass to call a protected BaseClass constructor, and you can obviously only do that if you are inside the constructor of DerivedClass.
You can call the base class contractor from the derived class's constructor.
Implementation:
public class A
{
protected List<int> MyList { get; }
public A()
{
MyList = new List<int>();
MyList.Add(1);
}
public int GetListCount()
{
return MyList.Count;
}
}
public sealed class B : A
{
public B() : base()
{
}
public A GetBase()
{
return (A)this;
}
}
Usage:
public class Program
{
public static void Main(string[] args)
{
B b = new B();
var a = b.GetBase();
Console.WriteLine(a.GetListCount());
}
}
This returns 1
... I am done with the derived class, but need to maintain the basic data ...
Well I wouldn't start from here... Instead of trying to solve this problem with inheritance, I would recommend solving it with composition.
Introduce a type to represent the structure of your basic data. Perhaps an interface to represent your basic functions (if any). Then your heavy resource classes can hold a reference to the basic data.
When you are done with the heavy class, you can keep a reference to the basic data and allow the heavy class to be garbage collected.

Manage derived classes via a base class when using GetComponent in Unity?

Whenever I try to set up an inheritance hierarchy, I find myself trapped in this scenario over and over.
In the current form, I have a base class that represent all UI elements in my game. I called this class, UI_Toggleable. This class has an enum property that each derived class can set. Here is brief look as to how the code looks like:
public class UI_Toggleable
{
// The Menu Type enum that all derived classes must define.
protected UIMenus menuType;
// Gives any child of this class a toggle function
// to enable/disable UI when needed.
public void ToggleUI()
{
// Toggle Code
}
// Public property Getter - Read Only Access.
// Only derived classes can define the value of the menu type.
public virtual UIMenus MenuType
{
get { return menuType; }
}
}
Now, say a class called InventoryUI derives from Toggleable, we have the following.
public class InventoryUI : UI_Toggleable
{
private void Awake()
{
_instance = this;
menuType = UIMenus.Inventory;
}
public override UIMenus MenuType
{
get { return menuType; }
}
}
Now, if I try to implement a manager for these objects, I will want to get the menu type of each derived class. However, I do not want to ASSUME the type of the UI_Toggleable class. Instead, what I am trying to do is to get any of the derived classes as a UI_Toggleable, and then proceed to call the MenuType method to get its type regardless.
UI_Toggleable toggleable = GetComponent<UI_Toggleable>();
toggleable.MenuType;
The problem with the above is, it would return me the MenuType of the base class instead of the derived class I retrieved as a base class. And that is somewhat expected, but I want to get the MenuType of the derived class WITHOUT doing the following:
if(GetComponent<UI_Toggleable>() is InventoryUI )
InventoryUI toggleable = GetComponent< InventoryUI >();
toggleable.MenuType;
The above works, but it defeats the purpose of me setting up a base class that shares similar properties with children. Doing all these casts and checks just makes the code appear difficult to read and decouple.
Other things I tried include the following:
Create an interface IMenuType that defines a function GetMenuType. Each derived class implements the method, and in my manager, I would do the check if(toggleable is IMenuType). And if true, then attempt to call ((IMenuType)toggleable).GetMenuType.
Let the MenuType property getter be an abstract function that each derived class must implement. But similar to the above cases, I still have to make cast checks before attempting to call the method.
Although not my priority, the MenuType method was not meant to be virtual.
You are not setting menuType of the base class correctly. Rather than setting it in the Awake method of derived classes, set it in the constructor, like this:
public class UI_Toggleable {
public UIMenus MenuType {get;}
// Subclasses must pass the correct menuType here
protected UI_Toggleable(UIMenus menuType) {
MenuType = menuType;
}
}
public class InventoryUI : UI_Toggleable {
// Pass the proper menu type for storing inside the base class
public InventoryUI() : base(UIMenus.Inventory) {
}
}
Note how MenuType is now a read-only property of the base class, rather than a virtual property with overriding.
I cannot really use the constructor. Is it acceptable if I set it in the Awake method instead?
It appears from your code sample that Awake is not being called in time for the base class to supply the correct value. In this case you go with an abstract getter-only property, like this:
public class UI_Toggleable {
public abstract UIMenus MenuType {get;}
}
public class InventoryUI : UI_Toggleable {
public override UIMenus MenuType {
get => UIMenus.Inventory
}
}
Note: Legacy syntax for get => UIMenus.Inventory is get { return UIMenus.Inventory; }

Using 'this' in base constructor?

I'm working on a project that involves a lot of interfacing and inheritance, which are starting to get a little tricky, and now I've run into a problem.
I have an abstract class State which takes in a Game object as a constructor argument. In my Game class's constructor, it takes in a State. The idea is that when inheriting from the abstract base Game class, when calling the base class's constructor, you give it an initial State object. However this State object takes in the same Game that you're creating it in. The code looks like this:
public class PushGame : ManiaGame
{
public PushGame() :
base(GamePlatform.Windows, new PlayState(this), 60)
{
}
}
However this doesn't work. I can only assume because the 'this' keyword is not usable until after the constructor has begun to execute. Trying to use it in your base class's constructor doesn't work, apparently. So what would be my best workaround for this? My plan B is to just remove the State argument from the Game class's constructor and just set the state inside the constructor code afterwards.
Is there an easier, less-intrusive way of doing this?
Clearly the ManiaGame class always uses objects of PlayState type, so you can move the creation at the ManiaGame level:
public class PushGame : ManiaGame
{
public PushGame() : base()
{
}
}
public class ManiaGame
{
PlayState ps;
public ManiaGame() {
ps = new PlayState(this);
}
}
If you want more concrete PlayState classes..
public class PushGame : ManiaGame
{
public PushGame() : base()
{
}
protected override PlayState CreatePlayState()
{
return new PushGamePlayState(this);
}
}
public class ManiaGame
{
PlayState ps;
public ManiaGame() {
ps = CreatePlayState();
}
protected virtual PlayState CreatePlayState()
{
return new PlayState(this);
}
}
public class PlayState
{
public PlayState(ManiaGame mg) {}
}
public class PushGamePlayState : PlayState
{
public PushGamePlayState(ManiaGame mg) : base(mg){}
}
If the State implementation used depends on the concrete Game class, then I would create a new instance of the State inside the constructor of the child Game class (PushGame) and access the State in the base class through the abstract property.
public class PushGame : ManiaGame
{
private readonly PlayState gamePlayState;
public PushGame() : base()
{
gamePlayState = new PlayState(this);
}
protected override State GamePlayState
{
get { return gamePlayState; }
}
}
public abstract class ManiaGame
{
protected abstract State GamePlayState { get; }
}
public class State
{
public State(ManiaGame mg) { }
}
public class PlayState : State
{
public PlayState(ManiaGame mg) : base(mg) { }
}
From the C# Language Specification
An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time error to reference this in an argument expression of the constructor initializer, as is it a compile-time error for an argument expression to reference any instance member through a simple_name.
i.e. this can only be used to reference another constructor in the context of a constructor initializer, as the reference to the current object instance won't be available until the construction is completed.
i.e. this can be only used as a scoping keyword before the constructor executes:
: this("ParameterForAnotherConstructor")
But it is not available as a reference to the class instance, since it has not completed construction
: base(this) // Keyword this is not available in this context
And obviously we can't call any instance methods from the constructor initializer either
: base(GetThis()) // Object reference is required
To solve OP's problem, changes to the base Mania class seems inevitable, given the two-way coupling between PlayState and ManiaGame (or subclasses of ManiaGame, like PushGame). There are many patterns available to decouple tight dependencies like this, such as the Dependency Inversion Principal (i.e. abstract the coupling between the classes), or the Observer pattern - (one of the two classes raises events or allows callbacks to be hooked (e.g. delegates or Actions), allowing the second class to 'observe' state changes without the hard coupling between them.
There is a similar Stack Overflow question, Keyword 'this' (Me) is not available calling the base constructor with a workaround similar to your suggestion.
Does your design differentiate between a game (say backgammon) and a game in progress (a game of backgammon)? If you're trying to mix these two concepts then I would suggest modeling them separately. For example, Backgammon and BackgammonContest.
I've recenly experienced this issue when trying to pass concrete instances of implemented interfaces via this to the base constructor.
To work around it, I simply implemented an abstract method on the base class that fetched the instance I was looking for:
public abstract class BaseClass
{
...
protected abstract IMyInterface GetInterface();
...
}
public class DerivedClass : BaseClass, IMyInterface
{
...
protected override IMyInterface GetInterface()
{
return this;
}
...
}
In my base class code, you can then use GetInterface (or whatever type you need) to obtain the instance:
public abstract class BaseClass
{
public void Foo()
{
GetInterface().DoSomething();
}
}

Accessing subclass in base class... but different

I have a base class that has a subclass (could be a struct i suppose but not sure if it's appropriate) and a method.
class Base
{
protected class SubClass
{
public string word;
public int number;
}
protected void SomeMethod()
{
this.SubClass.word //this is where I'm struggling
}
}
Then i have a couple child classes that implement my baseClass, instantiate the Base.SubClass and add some values to the instantiated class.
class ChildClass1 : Base
{
public childSubClass = new SubClass();
public void DoSomethingRidiculous()
{
childSubClass.word = "WhoFarted";
}
}
class ChildClass2 : Base
{
public childSubClass = new SubClass();
public void DoSomethingRidiculous()
{
childSubClass.word = "ItStinks";
}
}
If possible, I would like to be able to get the value of SubClass.word from within the Base class. I think that my attempt at implementing my idea is probably wrong.
I'm not sure that you really need subclassing / class nesting. Just move out class SubClass declaration and declare protected field/property of SubClass type instead.
public class SubClass
{
public string word;
public int number;
}
public class Base
{
protected SubClass subClassInstance = new SubClass();
protected void SomeMethod()
{
this.subClassInstance.word //this is where I'm struggling
}
}
Then you can access subClassInstance inside both ChildClass1 and ChildClass2
The base class has no field or property of type SubClass, so you definitely cannot do what you propose directly.
One solution would be to add the field
public childSubClass = new SubClass();
to class Base itself. Is there a problem with this?
The other solution would be to use reflection to get the value of the field, assuming that the object you are reflecting on does have such a field. This is really far-fetched and while it might technically allow you to do what you propose, it has a very bad code smell.
I'm not sure why you're making a Sub Class instead of just making those two properties of the base class, but the reason you're having trouble with this line :
this.SubClass.word //this is where I'm struggling
is because you're not instantiating SubClass as a property of the base class.
A base class can not (or should not) access members of derived classes, and usually not even know about derived classes (some exceptions apply, such as in the case of the State Pattern). If the base should have access to a member, it should be declared in the base. If derived classes should also be able to use that member, then mark the member as protected.
class Base
{
protected Foo someFoo;
void Frob()
{
// can access methods/properties of someFoo instance
}
}
class Child
{
public Child()
{
someFoo = new Foo(); // child can also access someFoo
}
}

Abstract class constructor in C#

In c# we can't create an obeject of a abstact class or interface it means abstract class do not have any constructor, is it true ?
or if it have then what is it's purpose there?
As others have said, abstract classes usually have constructors (either explicitly or the default one created by the compiler) - and any derived class constructor will have to chain through the abstract class's constructor in the normal way. That's the important bit... suppose you have an abstract class which stores the name associated with an instance - because you always want a name, and you don't want to write the Name property in each concrete derived class. You might provide a constructor which takes that name and assigns it to a field... and then every subclass constructor would have to go through that constructor, so that you still knew you'd always have a name. If you want to know more about constructor chaining, read my article on it.
Here's an example of that:
public abstract class DemoBase
{
private readonly string name;
public string Name { get { return name; } }
protected DemoBase(string name)
{
this.name = name;
}
// Abstract members here, probably
}
public class FixedNameDemo : DemoBase
{
public FixedNameDemo()
: base ("Always the same name")
{
}
// Other stuff here
}
public class VariableNameDemo : DemoBase
{
public VariableNameDemo(string name)
: base(name)
{
}
// Other stuff here
}
To further answer your comment on BoltClock's answer, asbtract classes can't have private abstract methods, but they can have private constructors. Indeed, it's sometimes useful to have only private constructors in an abstract class, because it means the class can only be derived from within the program text of the same class. This allows you to create pseudo-enums:
public abstract class ArithmeticOperator
{
public static readonly ArithmeticOperator Plus = new PlusOperator();
public static readonly ArithmeticOperator Minus = new MinusOperator();
public abstract int Apply(int x, int y);
private ArithmeticOperator() {}
private class PlusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class MinusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}
In this respect, an abstract private method/property could make sense - it could be accessed by the base class but provided by the derived classes within the same class's program text. However, it's prohibited by the specification. Usually, protected abstract members would solve the same problem - but not quite always.
Good question. Here's why Abstract classes need constructors even though they cannot be instantited.
In any Object oriented language like C#, object construction is an hierarchical process. Look at the code below. When you instantiate any object of type DerivedClass, it must construct the base object first before creating the object of typeof DerivedClass. Here the base class may or may not be an Abstract class. But even when you instantiate an object of a concrete type derived from an abstract class it will still need to call the constructor of the Base class before the object of DerivedClass type is created, hence you always need a constructor for Abstract class. If you have not added any constructor, C# compiler will automatically add a public parameterless constructor to the class in the generated MSIL.
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called..");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("DerivedClass constructor called..");
}
}
DerivedClass obj = new DerivedClass();
//Output
//BaseClass constructor called..
//DerivedClass constructor called..
PS: Assuming, If Abstract base classes
are not allowed to have constructors
because they need not be instantiated,
the whole fundamentals of the object
oriented programming will go on toss.
The idea behind Abstract types are to
represent objects that have some
features and behaviours but not
complete as whole to allow independant
existence.
No. it means that operator new is not allowed to create object from this type of class.
The purpose might be that are allocated/initialized some properties of class.
abstract usually leave some methods to implement.
Regarding the interface, this structure holds only the signatures of method, delegates or events. That may be implemented in class that use interface. You cant create a object.
Read about new
EDIT:
What is the purpose of constructor in abstract class ?
When one class inherit another class, the parent class of it had to be created first while object is crated. In class do not implement some special constructor always is used default one [className()]. When you override some method then the implementation of functionality is taken form class which override the method. This is why method used in constructor should never be virtual. Same logic for abstract class, such class can have a lot of functionality, and only one method that should be implemented by child class.
Abstract classes have constructors but you can't call them directly as you can't directly instantiate abstract classes.
To answer your comment, the concept of a private abstract method or property makes no sense, because private prevents anybody else from accessing it, and abstract prevents itself from accessing it. So there would essentially be no possible way to call it.
EDIT: see Jon Skeet's answer on private constructors. Private members of other kinds cannot exist in abstract classes, though.
Abstract classes do have constructors. When you create an instance of a derived class, its parent class' constructors are called. This applies to classes derived from abstract classes as well.

Categories