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.Ā Ā









