Reputation: 13785
I'm creating an abstract class to derive from. I have a Value
property that can be numerous data types. I saw an article on generics and I'm just wondering if my understanding is correct.
Does having an abstract:
BaseClass<T>
and inheriting it like:
InheritingClass: BaseClass<int>
basically equate to: anywhere there is a type T
defined in BaseClass , treat it as a type int
when used through InheritingClass?
That is my understanding and I just want to make sure that is correct before I build the rest of these classes and find out I was way off. This is the first time I've used generics.
Upvotes: 0
Views: 110
Reputation: 13419
anywhere there is a type T in InheritingClass , treat it as a type int
As already mentioned by @BoltClock, this is not the case. I wonder, however, if you meant to say:
anywhere there is a type T in BaseClass, treat it as a type int
If this is what you meant, then you are indeed correct.
Upvotes: 2
Reputation: 724132
No, it does not; it means your class specifically only inherits from BaseClass<int>
. If you define a generic type parameter T
in your InheritingClass
, like this:
InheritingClass<T> : BaseClass<int>
Then that type parameter pertains only to InheritingClass
and its own members, and does not apply to BaseClass
in any way. Neither does T
in InheritingClass
automatically resolve to int
due to the parentage. In other words, the two type parameters are independent of each other.
Upvotes: 5
Reputation: 710
Generics are for having type-safe classes that can be easily customized to be used with any type. The "T" is a placeholder for the type you want to use with that class.
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
"Generics allow you to define type-safe data structures, without committing to actual data types."
Upvotes: 0