tags:

views:

990

answers:

3

I have a class with both a static and a non-static interface in C#. Is it possible to have a static and a non-static method in a class with the same name and signature?

I get a compiler error when I try to do this, but for some reason I thought there was a way to do this. Am I wrong or is there no way to have both static and non-static methods in the same class?

If this is not possible, is there a good way to implement something like this that can be applied generically to any situation?

EDIT
From the responses I've received, it's clear that there is no way to do this. I'm just going to rename methods to use a different case so the methods are different.

+3  A: 

You can call static methods from instance methods without having to specify the type name:

class Foo
{
    static void Bar()
    {
    }

    void Fizz()
    {
        Bar();
    }
}

... so it makes sense that you wouldn't be allowed to have a static method and an instance method with the same signature.

What are you trying to accomplish? It's hard to suggest a workaround without knowing specifics. I'd just rename one of the methods.

Matt Hamilton
A: 

You can have static and instance method with the same name, as long as their declaration differs in the number or type of parameters. It's the same rule on how you can have two instance methods with the same name in a class.

Though technically, in the case of static vs. instance method, they already differ by the presence of the implicit this parameter in the instance method, that difference is not enough for the compiler to determine which of the two you want to call.

Update: I made a mistake. Return values are not enough to have different signature.

Franci Penov
Wrong: as long as their differ in the number and/or type of paramters. Return types don't overload.
asterite
[sigh] yeah, you're right...
Franci Penov
+10  A: 

The reason for the limitation is that static methods can also be called from non-static contexts without needing to prepend the class name (so MyStaticMethod() instead of MyClass.MyStaticMethod()). The compiler can't tell which you're looking for if you have both.

You can have static and non-static methods with the same name, but different parameters following the same rules as method overloading, they just can't have exactly the same signature.

ckramer