16.10.08

Mustoverride keyword on C# .NET with Generics

Recently I needed to ensure that every type that derives from my new type should override some methods.

For my surprise the VB.NET knows the mustoverride keyword but the C#.NET compiler doesn't!

By the way: "The mustoverride specifies that a property or procedure in a base class must be overridden in a derived class before it can be used" - Source MSDN

So how did I implement the mustoverride concept in C#?

Follow the rabbit!


Imagine that you've created a type named: OperationsManager.


public class OperationsManager
{
}



The OperationsManager type knows how process Operations.

The OperationsManager type should be a generic type that is parameterized by the Operation type.

But how do we specify that all derived types of OperationsManager must override some methods of the Operation type?

Answer: with Interfaces and the Generic's where clause.

Here's the plan:
1. Define an interface that all Operation types must implement: IOperation
2. In the OperationsManager type define in the where clause that all Operations must implement

public interfacw IOperation
{
void m1();
void m2();
}

public class OperationsManager<Operation> where Operation : IOperation, new()
{
public static Process()
{
Operation op = new Operation()
op.m1();
op.m2();
}
}



Now you can define n Operations and process them:


public interface IOperation
{
void m1();
void m2();
}

public class OperationsManager<Operation> where Operation : IOperation, new()
{
public static void Process()
{
Operation op = new Operation();
op.m1();
op.m2();
}
}

public class A : OperationsManager<A>, IOperation
{
public void m1(){Console.WriteLine("A.m1");}
public void m2(){Console.WriteLine("A.m2");}
}


public static void Main()
{
OperationsManager<A>.Process();
// or
A.Process();

}



Comments are welcome!

Be a part of our private list!

Enter your e-mail and access The Rabbit Way's exclusive offers.

Enter your Email


Preview | Powered by FeedBlitz

Or read this related articles



Widget by Hoctro | Jack Book

No comments:

Post a Comment