0

How can we implement static methods in interface...?

public interface ICache
{
  //Get item from cache
  static object Get(string pName);

  //Check an item exist in cache
  static bool Contains(string pName); 

  //Add an item to cache
  static void Add(string pName, object pValue);

  //Remove an item from cache
  static void Remove(string pName);
}

The above interface throws error: The modifier 'static' is not valid for this item

Sunil
  • 2,885
  • 5
  • 34
  • 41
  • Make it a normal interface and use something singleton like to implement it (not necessarily a standard singleton). Don't use static methods to create a cache. – CodesInChaos Apr 19 '13 at 10:14
  • You can't, http://stackoverflow.com/questions/259026/why-doesnt-c-sharp-allow-static-methods-to-implement-an-interface – Paul Aldred-Bann Apr 19 '13 at 10:14
  • 2
    No these are not same question. In the other question, the person derives from same Interface, but in the derived class he has a non static method. In this question, we want all derived classes to implement a static method. That basically serves as a contract. Anything that implements ICache has a static get method. I am not convinced by the answers. We could have this kind of contract or categorization... – Ozgur Ozturk Oct 02 '13 at 15:12

3 Answers3

4

And it's absolutely right. You can't specify static members in an interface. It has to be:

public interface ICache
{
  //Get item from cache
  object Get(string pName);

  //Check an item exist in cache
  bool Contains(string pName);

  //Add an item to cache
  void Add(string pName, object pValue);

  //Remove an item from cache
  void Remove(string pName);
}

(Your comments should be XML documentation comments, by the way - that would make them much more useful. I've added some whitespace between members to make the code easier to read. You should also consider making the interface generic.)

Why did you try to make the members static in the first place? What did you hope to achieve?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

You can't do it. It should be

   public interface ICache
    {
      //Get item from cache
      object Get(string pName);
      //Check an item exist in cache
      bool Contains(string pName);
      //Add an item to cache
      void Add(string pName, object pValue);
      //Remove an item from cache
      void Remove(string pName);
    }

Check out Why Doesn't C# Allow Static Methods to Implement an Interface?

Also Eric Lippert wrote a cool article series called

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

No, you can't... static methods/variables refer to the class itself not the instance of that class and since the purpose of interfaces is to be implemented by classes you cannot have static methods in a interface... it doesn't make sense

Stephan
  • 8,000
  • 3
  • 36
  • 42