Did it possible to cast a generic type of derived class to
generic type of base class?

Answer Posted / karthikeyant

Yes, it is Possible, if both are same type , But it is not
possible if both are diffrent type, below a gave sample
code describe things.

Example:

class BaseClassGenrics<T>
{

}

class DerivedClassGenrics<T> : BaseClassGenrics<T>
{

}

//-- correct one
DerivedClassGenrics<int> derivedClassGenrics = new
DerivedClassGenrics<int>();

BaseClassGenrics<int> gaseClassGenrics = new
BaseClassGenrics<int>();

gaseClassGenrics = derivedClassGenrics;


//-- Wrong one
DerivedClassGenrics<int> derivedClassGenrics = new
DerivedClassGenrics<int>();
BaseClassGenrics<string> gaseClassGenrics = new
BaseClassGenrics<string>();

gaseClassGenrics = derivedClassGenrics;

You get error like this : Cannot implicitly convert
type 'DerivedClassGenrics<int>'
to 'BaseClassGenrics<string>'

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How can i Spawn a Thread

525


What the different phase/steps of acquiring a proxy object in webservice?

473


What is the use of inheritance in c#?

487


can you allow a class to be inherited, but prevent the method from being over-ridden?

553


How many types of constructors are available in c#?

540






If a child class instance is created, which class constructor is called first - base class or child class?

507


Major difference between Basic httpbinding and WShttpbinding?

582


Why dictionary is faster than list?

556


What is desktop example?

489


Are attributes inherited c#?

467


Is cli same as the clr?

520


What are the different types of classes?

478


How do generics work in c#?

488


What is application c#?

500


What is Custom attribute? How to create? If I'm having custom attribute in an assembly, how to say that name in the code?

514