Epsiloncool Epsiloncool - 11 months ago 47
C# Question

A way to extend existing class without creating new class in c#

I have a good complete class which is doing awesome things. I need to allow users to use this class by replacing some methods in it, but inheritance is not allowed, because this class also used in other application classes.

It is like you have a class which creating a table, but you need to allow users to redefine method which is creating table cell to let the user print something custom in this cell. The class, however, has a default way to print the cell content (in case the user do not need to customize it).

Is there any common-used or standartized way to achieve this?

Answer Source


Having had "the peanut gallery" point out that my approach (at bottom) wouldn't fit the bill, here's another way:

Use delegation. Define certain public properties with type Action or Func. Where these behaviors need to be invoked in your code, compare the properties to null. If null, use your default behavior. If not, invoke the values.

Your calling code MAY set the properties, but doesn't have to.

(first try) Alternative approaches:

You are describing an extension method, or the use of inheritance if that's available.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.


Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (or pillars) of object-oriented programming. Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.


You can't derive from all .NET types, but you can write extension methods for them.