Is there a way to accomplish something like List <object> list = new List <int> () in C #?

That's the question. What I want to accomplish is similar to the following Java code:

class A { }
class B extends A { }

public class Tests {
    public static void main(String [] args) {
        ArrayList<? extends A> lists = new ArrayList<B>(); 
    }
}

      

(where B extends A

means B inherits from A)

Is it even possible?

thanks

+2


a source to share


2 answers


No. While C # 4.0 introduces the concept of variance for interfaces, it cannot (and cannot) do what you are asking specifically.

In C # 4.0, you can do this:

IEnumerable<object> foo = new List<int>();

blow>


Edit: As Mark points out, this cannot be done with type values ​​and reference types. However, since I think your question was more about generalized A:B

than about int:object

, I think this point carries. To be precise, I mean that C # 4.0 will allow something like this:



IEnumerable<object> foo = new List<string>();

      


But you cannot do what you describe. Namely, consider:

List<int> foo = new List<int>();
List<object> bar = foo;

bar.Add("baz");

      

Now what happens when we try to access foo[0]

? You have now violated the type safety of the list.

+7


a source


Best used List<object>

to just use non-generic IList

:

IList list = new List<int>();

      



But! Adding anything other than int

will throw the runtime exception.

+4


a source







All Articles