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

Answers were Sorted based on User's Feedback



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

Answer / 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

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

Answer / lalit pradhan

Good explaination Karthikeyant :)
Also in addition to that the following cast is also not
possible. It will compile but give you casting error on
compile time.

DerivedClassGenrics<int> derivedClassGenrics = new
DerivedClassGenrics<int>();

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

derivedClassGenrics = (DerivedClassGenrics<int>)
baseClassGenrics;

Enjoy!!!
Lalit Pradhan a.k.a DOTNET Gadha

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More C Sharp Interview Questions

How assembly versioning in .NET prevent DLL Hell problem?

0 Answers   DELL,


Is there throws keyword in c#?

0 Answers  


How do you declare an arraylist?

0 Answers  


What is the difference between a variable and a literal?

0 Answers  


Explain manifest & metadata?

5 Answers   IBM, Wipro,


What is c# in asp net?

0 Answers  


What are the properties in c#?

0 Answers  


Why objects are stored in heap in c#?

0 Answers  


How to use the sreamReader class to read form a text file?

0 Answers   MCN Solutions,


Why do we need static class in c#?

0 Answers  


what are nullable types in c#

0 Answers   Cognizant,


What is exe in c#?

0 Answers  


Categories