1

I am looking for a equivalent syntax for java code below in C#.

ArrayList<Class <? extends A>> list = new ArrayList<Class<? extends A>>();
// Sample usage
list.add(A.class);
list.add(B.class); // B extends A

The list above basically only accept Sub Class of A (or A) as input.

Thank in advance.

2 Answers 2

2

There's no equivalent for that in C#. The generics in C# are quite different to those in Java in various ways, including the way covariance and contravariance work.

You could have a generic method (or generic type) with a constraint on the type parameter like this:

public void Foo<T>(IList<T> list) where T : SomeClass

or

public class Foo<T> where T : SomeClass

... but Type itself (the .NET equivalent of Class<T>) is non-generic, so there's no way of saying "This is a list of types which extend A".

If you give us more information about what you're trying to achieve, we may be able to help you more.

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

2 Comments

I have a dictionary Dictionary<string, Type>, it works, I just wanted add more constraint and less casting. thanks for your answer.
@PeirHwa.Soo: Unfortunately there's no way of doing that :( I would validate the type before you put it into the dictionary, and then just trust that the cast will work later.
0

The C# language has generics from version 2.0 onwards:

http://msdn.microsoft.com/en-us/library/512aeb7t.aspx

Type constraints can be found here:

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

I'm mostly a Java programmer not a C# one so I'm not sure the exact syntax of what you need but you should be able to find it from there.

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.