Thursday, July 10, 2008

Static virtual in C#

Argh, this is annoying. I need a Handler type with a virtual string GetProduct() method so that derived types "know" what product they are for. However, I don't want to have to create an instance of the actual class every time I need to ask for its product... I want it to be a virtual method. Too bad - C# doesn't allow virtual static methods.

What I ended up with was this: each class derived from Handler has a read-only static string property Product, each of them returning the product that class can handle. In the method where I need that product (when populating a drop-down for example) I use reflection to get the value of the property:

  1. if (handlerType.BaseType != typeof (Handler))  
  2.   return;  
  4. var product = (string) handlerType.GetProperty("Product").GetValue(nullnull);  

I'm not really happy with this - I miss Delphi's "class" type which allowed a much more elegant solution. I'll edit this if I find something I like better.

Edit: Heh, I found a solution I like better: attributes. I define the following class:

  1. [AttributeUsage(AttributeTargets.Class)]  
  2. internal class ProductInfo: Attribute  
  3. {  
  4.   public string Product { getprivate set; }  
  6.   public ProductInfo(string product)  
  7.   {  
  8.     Product = product;  
  9.   }  
  10. }  

Now I can decorate the handlers with a
attribute and extract the product name with

  1. var attributes = handlerType.GetCustomAttributes(typeof (ProductInfo), true);  
  2. if (attributes.Length == 0)  
  3.   return;  
  5. var product = ((ProductInfo) attributes[0]).Product;  

First time I create a custom attribute. Helpful and elegant, so it won't be the last.

No comments: