Hi I am new to C# generics , what is the right way to rewrite the following code in C# ?
public class A <T extends Base>{
Map<Class<T>,Object> m = newHashMap();
}
Finally, I think I got your intent properly.
public class A<T> where T : Base
{
Dictionary<Type, T> m = new Dictionary<Type, T>();
}
No type erasure in C# so you are going to have to change a bit of code.
Dictionary<Type<T>, object> m;T is string, you will be able to map "some text" to new object() which is not what the OP asked for.Class<String> s = "asdf".getClass(); vs. String s = "asdf" - those two are not the same.Class<? extends String> (well you can get the same for method parameters)As already said in the other posts, the C# equivalent of class A<T extends Base> is class A<T> where T : Base. But unlike java.lang.Class, the C# class System.Type is not generic, so there is no equivalent for the concept of Class<? extends Base> in C#. Your options are reduced to:
public class A<T> where T : Base
{
Dictionary<Type, object> m = new Dictionary<Type, object>();
}
Now you may have:
public class Sub1 : Base {}
public class Sub2 : Base {}
....
m.Add(typeof(Sub1), new object());
m.Add(typeof(Sub2), new object());
But unfortunately also:
m.Add(typeof(string), new object());
Your best choice is to make sure that m is duly encapsulated so that this won't happen.
You'd achieve this using constraints, as described here: http://msdn.microsoft.com/en-us/library/d5x73970
public class A<T>
where T : Base
{
}