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
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 |
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 |
What are the boolean data types in c#?
How to add controls dynamically to the form using c#.net.
What is constants in c#?
interface a { Method1() Method2() } class b: a { override Method1() override Method2() } what will happen & why?
What are the 2 broad classifications of data types available in c#?
Which function is the entry point for a DLL in MS Windows 3.1?
What is a linked list c#?
What is entity framework in c#?
What is definition in c#?
What is serialization in c#?
Can you prevent your class from being inherited and becoming a base class for some other classes?
Can an interface inherit class/abstract class.