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 are the boolean data types in c#?

0 Answers  


How to add controls dynamically to the form using c#.net.

0 Answers  


What is constants in c#?

0 Answers  


interface a { Method1() Method2() } class b: a { override Method1() override Method2() } what will happen & why?

5 Answers  


What are the 2 broad classifications of data types available in c#?

0 Answers  






Which function is the entry point for a DLL in MS Windows 3.1?

0 Answers   3i Infotech,


What is a linked list c#?

0 Answers  


What is entity framework in c#?

0 Answers  


What is definition in c#?

0 Answers  


What is serialization in c#?

0 Answers  


Can you prevent your class from being inherited and becoming a base class for some other classes?

5 Answers  


Can an interface inherit class/abstract class.

1 Answers   Synechron,


Categories