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 datareader c#?

0 Answers  


What is toint32 c#?

0 Answers  


What are the properties in c#?

0 Answers  


What?s a delegate?

2 Answers  


When you inherit a protected class-level variable, who is it available to?

4 Answers   Visual Soft,






Is there an equivalent of exit() for quitting a c# .net application?

0 Answers  


What is private class in c#?

0 Answers  


Explain code compilation in c#.

0 Answers  


Is it not possible to store a boolean value as a variable?

0 Answers  


What is tuple in c#?

0 Answers  


What is console programming language?

0 Answers  


Define c# i/o classes?

0 Answers  


Categories