1

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();

}

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

21 Comments

should be something like Dictionary<Type<T>, object> m;
I don't think so, in your code if T is string, you will be able to map "some text" to new object() which is not what the OP asked for.
@Cicada you sure about that? In Java Class<T> mean literal/type of class T, not Object of class T
Class<String> s = "asdf".getClass(); vs. String s = "asdf" - those two are not the same.
@O.R.Mapper So the real problem is that we can't specify bounded wildcards in C#, not type erasure. I.e. there's no equivalent concept of Class<? extends String> (well you can get the same for method parameters)
|
1

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.

Comments

0

You'd achieve this using constraints, as described here: http://msdn.microsoft.com/en-us/library/d5x73970

public class A<T>
  where T : Base
{
}

Comments

0

Using type constraints, like this:

public class A<T> where T : Base {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.