C# Calling template base class in an override, or Paying for something with your parents money
Template, or Generic, classes in C# are a handy way of providing type safety, Template classes also help code look clean and readable (As anyone who has coded in KNR C or C++ with complex types.
There will be occasions when you want to extend a template class. Â
I recently wanted to extend one of the basic template classes in C#
public class FunList : LinkedList<MyType>
{
    // ToString is a static function, overriding can be done simply
    // by using the override keyword
    public override string ToString()
    {
        // Do stringy thingsÂ
    }
    // Clear is not a static function,Â
  // meaning that it fiddles with internal variables, that means state Â
    public new void Clear()
    {
    // Handy way to call parent class in over-ride, works for templates too        ((LinkedList<MyType>)this).Clear();
    }
}
So, the trick is knowing if the function you are calling diddles class state variables. For classes you donât write, you get to rely on the compiler to tell you how you override.Â
There are two keywords you can use to override a base class, ânewâ and âOverrideâ
âOverrideâ should not be used for functions that modify the state of the class, most of the libraries functions are declared such that you canât override functions that mess about with internal variables.Â
New use for New
This was a new one on me (pun trifecta), using the keyword new in the declaration of a function overrides and supersedes a parent classâs function with the same name. In this example overriding the base LinkList<T> classâs Clear() function.Â
Come to your own rescue: Typecast yourself.Â
One of the benefits of templates is that you donât have to typecast parameters and return values, but how the hell do you get a handle on the instance of your parent class when you are overriding... When you type cast âthisâ to the type of your Base Class vola, you have a pointer to the instance of your base class.Â
So if you find yourself calling an instance of a template class over and over. Or you find yourself associating variables and functions with use of a template class, Feel free to create a derived template, it really is easy. Â

















