1

I have a class which is handling objects same way. It's like:

class Handler<T>{
    private T _obj;
    public T obj{
        get{
            ...//do sth
            return _obj;
        }
        set{
            ...//do sth
            _obj = value;
        }
    }
    ... // some other properties, no T anymore
}

There are large amount of code working on Handler objects, ignoring type. I mean, type T is not for them, there are setting other fields. There are containers with Handler<> and so on.

At the end I need to return Handler with correct type.

I wanted to use Handler<object>, but there is no way I know to convert it to Handler<SomeClass>.

How can I handle situtations like this?

Ari
  • 3,101
  • 2
  • 27
  • 49

2 Answers2

3

Why don't you make a base class for Handler<T>, which will contain all non-generic code?

class HandlerBase
{
   // some other properties
}

class Handler<T> : HandlerBase
{
    public T obj { ... }
}

If your "large amount of code" ignores T, than let it work with HandlerBase.

Dennis
  • 37,026
  • 10
  • 82
  • 150
0

You can try with an IHandler interface.

IHandler<SomeClass> h1 = new Handler<SomeClass>();
IHandler<Object> h2 = h1;

This will work !
More info on Covariance on MSDN

knaki02
  • 183
  • 11