-2

i have this class

class Class1
{
    public static List<int> abc = new List<int>();

}

so now i can access from outside the class :

public void x()
    {
        Class1.abc.Add(2);
    }

what i want to do is : I want "Class1" implement from INTERFACE and implement this "abc" that i can do Class1.abc.Add(2);

i mean that the abc will be on interface..

I already try to do this but i not without any success how can i do this please? thanks!

dani1999
  • 89
  • 2
  • 10
  • You say "i mean that the abc will be on interface", can you please explain that in more details? – Yacoub Massad Dec 09 '15 at 20:50
  • Interfaces can't have static members. An interface isn't a class, so you can't create instances of it, and there's no code in an interface, just method & member declarations. – Tony Vitabile Dec 09 '15 at 20:52
  • an object can't be an interface, I think what you are trying to accomplish can't be done staticly. – Dan Dec 09 '15 at 20:53
  • 1
    it's not possible: https://stackoverflow.com/questions/259026/why-doesnt-c-sharp-allow-static-methods-to-implement-an-interface the link is for methods, but the same holds for properties – thumbmunkeys Dec 09 '15 at 20:53
  • i cant do properties get; set; on interface? – dani1999 Dec 09 '15 at 20:57
  • Sure, you can define instance properties in an interface, just not static properties or other members. – Tony Vitabile Dec 09 '15 at 21:06

1 Answers1

2

As others have said, only objects can implement interfaces in C#. See Why Doesn't C# Allow Static Methods to Implement an Interface? for a good explanation.

Instead, you could use the Factory (an object that use used to create other objects) or Singleton patterns (use a single instance of an object). These could implement an interface including the "Add" method you mentioned.

For example, instead of:

class Class1
{
    public static List<int> abc = new List<int>();
}

Class1.abc.Add(1); // Add numbers

... have something like ...

interface IListInterface
{
    List<int> List;
}

class Lists: IListInterface
{
    public Lists()
    { 
        List = new List<int>();
    }

    public List<int> List
    {
         get;
    }
}

// Using the above
public void AddToList(IListInterface lists, int a)
{
    lists.List.Add(a);
}

This standardize your access to the lists by using an interface and allows you to swap the implementation of the list interface without affecting the using code, useful for automated testing.

Community
  • 1
  • 1
akton
  • 14,148
  • 3
  • 43
  • 47