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 is encapsulation in csharp?
What are the 2 kinds of data type conversions in c#?
Why abstraction is used in c#?
What is difference between events and delegates?
Is c sharp open source?
What are virtual methods? How are they used?
What is the difference between readonly and const
How to prevent the error while updating ui control from another thread?
Is c# queue thread safe?
What is the difference between firstordefault and singleordefault?
What is constants in c#?
Which operator cannot be overloaded in c sharp?