Reputation: 3681
public DerivedClass : BaseClass
{
// code
}
DerivedClass B = (DerivedClass)MethodReturnsBaseClassObject();
B.DoWork();
There are many Derived classes being inherited from BaseClass
. So everytime i need to write a new method to use some of the properties.
Is this possible that using reflection we make DerivedClass
type dynamic and do something like this and make it generic.
System.Type type = GetRequestFromSession().GetType();
type B = (type )MethodReturnsBaseClassObject();
Console.WriteLine( B.Name);
Console.WriteLine( B.Age);
any help is appreciated.
Upvotes: 1
Views: 934
Reputation: 9587
You can have safe access to members of the derived type (without casts) while enforcing the base class constraint if you employ a generic method with the following signature:
public TDerived MethodReturnsDerivedObject<TDerived>()
where TDerived : BaseClass
Your calls will then look like this:
DerivedClass b = MethodReturnsDerivedObject<DerviedClass>();
b.ExecuteSomeMethodDefinedInBaseClass();
Console.WriteLine(b.SomePropertyDefinedInDerivedClass);
Upvotes: 5
Reputation: 1643
I would go with Kirill Shlenskiy's answer for now. But I'd also like to suggest moving this method onto the base class itself if it makes sense to do so. There may be tangled dependencies or other weirdness that prohibits this solution, but it may also allow you to have one consumer without using generics.
Upvotes: 2
Reputation: 157098
This feels like bad design to me: you make something generic that you use as something that isn't. Maybe you should rethink your design.
For what your question is concerned, maybe you can create a proxy method or class that returns the type you expect. This is only useful when there is a low number of methods you call.
Another option is to use the dynamic
keyword, but I would advice only to use that if nothing else works.
Upvotes: 3