Question

I have an interface which is being used like this:

var descr = new IMyInterface[3];

At first glance I thought that this doesn't make any sense since it looks like an Interface is being instantiated (which isn't possible). So I think that this is probably a call to an Indexer defined in the interface but I still don't quite understand how this works. So my question is:

  1. What is this call doing? Is it calling an indexer defined in the interface?
  2. What implementation of the interface's indexer is being used?

Thanks for the help :)

Was it helpful?

Solution

You are creating an array of 3 IMyInterface... but each item is null in the array.

OTHER TIPS

It's creating an array of IMyInterface with three elements. i.e. a IMyInterface[]. This is just the usual new T[n] syntax for array creation, no different from new int[3].

Conceptually it's the something similar to new Array<IMyInterface>(3), except that array is no generic type for historical reasons.

An array is a concrete class, so you can create an instance of it, even if the member type is an interface. The members will be initialized to default(T) which is null for interfaces.

This is unrelated to indexers.


It is possible to define indexers on interfaces just like you can do it on classes. But the syntax for using them does not involve new.

It's also possible to instantiate interfaces in certain COM related scenarios.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top