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

Viewed 19494

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.

7 Answers

First, the only thing the 'new' keyword actually does is prompt the compiler to NOT produce a warning that you should use the 'new' keyword. Apart from getting rid of the warning, the keyword itself does nothing (in the context in question).

Now, the compiler WANTS you to use the 'new' keyword when you redefine a member (property or method) already defined in an interface you inherit from, and there are at least two possible reasons for doing this. First, as Eric Lippert mentioned above, you may want a method to return a different type (or define a property of the same name with a different type). Another possibility is if you want to define different implementations for the two interfaces:

interface A
{
    void a();
}

interface B : A
{
    new void a();
}

class C : B
{
    void A.a() { Console.WriteLine("Called by interface A!"); }
    void B.a() { Console.WriteLine("Called by interface B!"); }
}

static class Test
{
    public static void DoTest()
    {
        B b = new C();
        b.a();       // Produces "Called by interface B!"
        ((A)b).a();  // Produces "Called by interface A!"
    }
}

If you try to define B.a() in C without redefining a() in B, you get a warning that it is not a member of interface: explicit interface declaration requires that you use an interface for which the member is explicitly defined.

Related