Do special processing for a type in a generic class

Question!

Do special processing for a type in a generic class Pinnew member dan neely 19mins ago

I'm trying to roll up some old (originally .net 1.1) abstract classes into generics. The classes in question all provide similar functionality for a data object of a specific type. For the most part things are going well, but I've ran into a few places where one one of the data objects is of a type that needs extra processing in one method beyond what all the other types need. I can check the type of T to see if it's the type I need to do the special processing for, but the cast from T to SpecialType won't compile. Is there a different way I can do this, or is what I want to do impossible?

class MyGenericClass : ICloneable where T: class, new()
{

private T  m_storedClass;
...

private DoStuff()
{
   //do stuff for all types

   //objects of SpecialType need extra stuff done.
   if (typeof(T) == typeof(SpecialType))
   {
      //compiler error:  Error Cannot convert type 'T' to 'SpecialType'
      ((SpecialType)m_storedClass).SpecialString = "foo";
   }
}
By : Dan Neely


Answers

This won't work unless you do this

class MyGenericClass : ICloneable 
    where T: class, new(), SpecialType

or this

class MyGenericClass : ICloneable 
    where T: class, new(), BaseTypeOfSpecialType

or maybe this:

class MyGenericClass : ICloneable 
    where T: class, new(), InterfaceOnSpecialType

Perhaps you don't need to do this though - if you post a more complete problem maybe I can help you figure out a way to avoid having to do this at all.



You could make it work by using constraints, but this code has a funny smell to it.

Is there another way you could get that extra processing in there without breaking the "genericness" of your class?



It doesn't work in C#, the compiler won't let you do that... If you can't live with the interface/base class constraints that others have suggested, I have a not-so-nice but working solution:

The cast you're trying to do works in C /CLI. You have to decide for yourself if it's worth it.

By : chris166


This video can help you solving your question :)
By: admin