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 datareader c#?
What is toint32 c#?
What are the properties in c#?
What?s a delegate?
When you inherit a protected class-level variable, who is it available to?
Is there an equivalent of exit() for quitting a c# .net application?
What is private class in c#?
Explain code compilation in c#.
Is it not possible to store a boolean value as a variable?
What is tuple in c#?
What is console programming language?
Define c# i/o classes?