monish001
monish001

Reputation: 690

Typecasting base class reference to its actual type

I have a Class BaseFilter and a number of Derived classes of BaseFilter class.

1. List<base> list = getFilters();
2. foreach(Base filter in list){
3.     var filterType = filter.GetType();
4.     var filter1 = filter as filterType;
5.     //DO SOME DERIVED CLASS OPERATION
6. }

I am getting error at code line 3. The challenge is filter can be of any derived class type. Is there any way to typecast the filter object to its actual derived class?

I am getting following error: The type or namespace name 'filterType' could not be found (are you missing a using directive or an assembly reference?)

What should be the correct way to do it?

Upvotes: 2

Views: 958

Answers (2)

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

As Jon Skeet already stated, you cannot cast to type without knowing the type. However, if you have a small number of derived classes you know at compile time, you could do something like this:

List<base> list = getFilters();
foreach(Base filter in list)
{
   if(filter is DerivedFilter1)
   {
      var derived1 = filter as DerivedFilter1;  
      // do some DerivedFilter1 specific operations
   }
   else if(filter is DerivedFilter2)
   {
      var derived2 = filter as DerivedFilter2;  
      // do some DerivedFilter2 specific operations
   }
   else 
   {
      // do some general operations
   }
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500385

Is there any way to typecast the filter object to its actual derived class?

No. You have to know the type you're trying to cast to at compile-time.

If you don't know that type, how can you know which operation to perform? If you perform the same operation on all the types, that operation ought to be present (possibly in an abstract form) in the base class.

Basically, at the moment your request isn't a useful one - but if you could provide more details about what you're actually trying to do, and why you think a "cast to the actual type" would be appropriate, we may be able to help you more.

In some cases, you might find that using dynamic will help - but I'd only use that as a last resort, after cleaner approaches have failed - and we can't advise you on those cleaner approaches without knowing what you're trying to achieve.

Upvotes: 6

Related Questions