Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static and Instance methods with the same name?

Tags:

c#

.net

oop

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 going with a different naming system to work around this problem.

like image 871
Dan Herbert Avatar asked Oct 01 '08 22:10

Dan Herbert


People also ask

Can static and non static method have same name?

A static and non static method can't have the same signature in the same class . This is because you can access both a static and non static method using a reference and the compiler will not be able to decide whether you mean to call the static method or the non static method.

Can a static method use instance variables in the same class?

Because a static method is only associated with a class, it can't access the instance member variable values of its class.

Can we have static method with same name both in parent and child class?

The answer is 'Yes'. We can have two or more static methods with the same name, but differences in input parameters.

Can an instance method be static?

Static methods can't access instance methods and instance variables directly. They must use reference to object.


2 Answers

No you can't. 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.

like image 138
ckramer Avatar answered Sep 17 '22 08:09

ckramer


Actually, there kind of is a way to accomplish this by explicitly implementing an interface. It is not a perfect solution but it can work in some cases.

interface IFoo {     void Bar(); }  class Foo : IFoo {     static void Bar()     {     }      void IFoo.Bar()     {         Bar();     } } 

I sometimes run into this situation when I make wrapper classes for P/Invoke calls.

like image 26
andasa Avatar answered Sep 21 '22 08:09

andasa