Alex Rivera | Logout

Easiest way to make C# not instantiate a class unless inherit?

Asked 2010-01-14T19:15:32.763
12

What is the easiest way to make C# not instantiate a class unless inherit?

Sounds weird but i dont want to explain the why. I have a base class and two class that inherit it. I want to use the derived class only and not the base. The derive class does not have any extra functions. Whats the easiest way to NOT allow me to write new BaseClass(); so i dont accidentally use it? I do have functions that operate on the base class and not the derived.

Edit
Report

1 Answer

1

The way you describe your need, making your class abstract is the way to go. It will stop you from instantiating the base class and will allow you to call the functions on it. This will also allow you to mark functions and properties as abstract and force the inherited classes to implement them.

If you had no need to share code, an interface would be a nice option. It allows you to implement it in a way very similar to an abstarct class and casting your implementations into it.

Hope this adds some value.

answered 2010-01-14T20:45:09.430

Your Answer