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 |
6. If we assign a value in textbox on Page_UnLoad event, will it display?
Why do we need to override in c#?
Can we inherit partial class in c#?
Which compiler switch creates an xml file from xml comments in the files in an assembly?
Do loops in c#?
Why singleton is sealed?
Can we inherit a private class in chsarp? how? explain(with code) ?
Explain how to parse a datetime string?
How can an inner class access the members of outer class?
What is deadlock in c#?
Describe how a .net application is compiled and executed
What is the difference between array.find method and arraylist.find method?