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

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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is difference between array and arraylist in c#?

641


Explain the difference between Metadata and Manifest

732


What is addressof operator?

712


You are designing a user control. You created new property called backgroundimage which is of type image. You wanted to disable storing this property in the user’s form. How to achieve this?

716


These questions were asked me in a technical interview: •If we deploy an application on multiple server (like database server, web server) then, each request should be redirected to proper server, then how you will handle it in your code? •How security pinholes will be handled in an application? •What things should be considered while writing a web application? •How will you do load/performance testing of web application? Which framework you will use for it? •How will you implement a cache for results which require a DB access? Please let me know how to write an web application considering all these points. I am not so much aware of architechural design of web application. Your guidelines will be helpful.

2734


what are the contents of an assembly ?

733


How do I simulate optional parameters to com calls?

717


What do you mean by stack and heap in c#?

655


What is Web.config?

736


What's the difference between class and object?

680


What is a dll in c#?

632


What is firstordefault c#?

720


Can an array be null c#?

697


How can I access the registry from c# code?

701


Howmany five tracing levels in System.Diagnostics.TraceSwitcher? Why they are using?

725