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

Can an int be negative c#?

683


Is concurrent queue thread safe?

571


How do I register my code for use by classic com clients?

585


Why do we use parameters in c#?

588


What is callback in c#?

563






Explain the ways to deploy an assembly?

603


Explain About web methods and its various attributes

608


Difference between Value type & reference types ? and give the example in .Net?

612


What is master page in asp net c#?

565


What are some examples of desktop applications?

580


What is gac? What are the steps to create an assembly and add it to the gac?

573


Is c# difficult to learn?

550


What is writeline?

566


What is the difference between null and string empty in c#?

537


What is instantiating a class?

598