What does 'new' keyword mean when used inside an interface in C#?

Ivan picture Ivan · Jul 5, 2011 · Viewed 15k times · Source

Developing an interface generic I wished to declare a constructor in an interface but it says constructors are forbidden there. I've tried to declare a static factory method then, but it says neither static methods are allowed and suggests using 'new' keyword. But I have hardly any idea of what could 'new' keyword exactly mean when used inside an interface in C#. Have you?

UPDATE:

I didn't post any sample code because I didn't want to mix 2 questions - how to specify a constructor/factory in an interface AND what does the 'new' keyword mean in interfaces. I I even was only forced to specify the first part because StackOverflow didn't accept the second question in pure form, saying it doesn't meet quality standards.

But, as you demand, I'll sample what I was trying to acheive:

Interface IMyInterface <T, U, V>
{
    IMyInterface (T, U, U);
    // OR
    static IMyInterface GetNewIMyInterface (T, U, U);
}

I just want every derived class to implement such a constructor.

Answer

Eric Lippert picture Eric Lippert · Jul 5, 2011

Bala's answer is correct, but it might be helpful to see why you'd want to do this. Consider the problem that the BCL designers were faced with when designing the libraries for CLR version 2. There was an existing interface:

interface IEnumerable
{
  IEnumerator GetEnumerator();
}

Now you want to add:

interface IEnumerable<T> : IEnumerable
{
  new IEnumerator<T> GetEnumerator();
}

The new interface differs from the old solely in the return type.

What are your choices?

1) Mark the new GetEnumerator as "new" so that the compiler knows that this is intended to be the new method that does not conflict with the old method of the same name but different return type.

2) Change the name to GetEnumerator2.

3) Don't inherit from the original IEnumerable.

Options 2 and 3 are awful. Option 1 is awesome: new enumerables work seamlessly with code that expects old enumerables, but code written to use the new enumerables get the "new" generic behaviour by default.