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

What is encapsulation in csharp?

0 Answers  


What are the 2 kinds of data type conversions in c#?

0 Answers  


Why abstraction is used in c#?

0 Answers  


What is difference between events and delegates?

0 Answers  


Is c sharp open source?

0 Answers  






What are virtual methods? How are they used?

3 Answers   TCS,


What is the difference between readonly and const

4 Answers   Emphasis,


How to prevent the error while updating ui control from another thread?

0 Answers  


Is c# queue thread safe?

0 Answers  


What is the difference between firstordefault and singleordefault?

0 Answers  


What is constants in c#?

0 Answers  


Which operator cannot be overloaded in c sharp?

0 Answers  


Categories