I'm studying generics types in C#, and I have found this MSDN article http://msdn.microsoft.com/en-us/library/sz6zd40f.aspx about generic classes. Almost everything is OK, but I have a doubt respect to closed constructed type concept.
So, I decided to write some test code to explore the concept:
using System;
using System.Collections;
namespace Articulos.Cap03
{
internal class ClaseBase <T> { }
internal class SubclaseGenerica<T> : ClaseBase <long> { }
internal class HerenciaCerrada
{
public static void Main()
{
SubclaseGenerica<decimal> sg1 = new SubclaseGenerica<decimal>();
SubclaseGenerica<Object> sg2 = new SubclaseGenerica<Object>();
SubclaseGenerica<ArrayList> sg3 = new SubclaseGenerica<ArrayList>();
}
}
}
It compiles and executes correctly.
What is the porpuse of:
internal class SubclaseGenerica<T> : ClaseBase <long> { }
[Note: I thought it restricts the parameter type of SubclaseGenerica to long
primitive type.]
Well, this is certainly an odd declaration:
internal class SubclaseGenerica<T> : ClaseBase <long> { }
In this case, it's a generic type - so it's declaring a new type parameter T
. However, it's supplying a type argument of long
for ClaseBase
. So you could write:
ClaseBase<long> foo = new SubclaseGenerica<string>();
and that would be fine. Any code within ClaseBase
would see (at execution time) that T
was long
, and any code within SubclaseGenerica
would see (at execution time) that T
was string
, because they're two different type parameters.
See more on this question at Stackoverflow