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

6. If we assign a value in textbox on Page_UnLoad event, will it display?

2 Answers   Mphasis,


Why do we need to override in c#?

0 Answers  


Can we inherit partial class in c#?

0 Answers  


Which compiler switch creates an xml file from xml comments in the files in an assembly?

0 Answers   Siebel,


Do loops in c#?

0 Answers  






Why singleton is sealed?

0 Answers  


Can we inherit a private class in chsarp? how? explain(with code) ?

4 Answers   Techno Labs,


Explain how to parse a datetime string?

0 Answers  


How can an inner class access the members of outer class?

0 Answers   Changepond,


What is deadlock in c#?

0 Answers  


Describe how a .net application is compiled and executed

0 Answers  


What is the difference between array.find method and arraylist.find method?

1 Answers   Mphasis,


Categories