1

I'm used to Objective-C and so I know that to create a singleton method all I do is this:

+ (void)myMethod

and to call it I type

#import MyClass;
[MyClass myMethod];

How do I do the same thing in C#?

Ethan Allen
  • 14,425
  • 24
  • 101
  • 194
  • That's not a singleton in objective-c, that's a class method. – bryanmac Dec 10 '11 at 02:04
  • possible duplicate of [What is a singleton in C#?](http://stackoverflow.com/questions/2155688/what-is-a-singleton-in-c) – bryanmac Dec 10 '11 at 02:06
  • The `+` indicates that it's a class method (vs an instance method). – Hot Licks Dec 10 '11 at 02:09
  • the + is a class method. Here's one way to do an objective-c singleton http://stackoverflow.com/questions/5381085/how-to-create-singleton-class-in-objective-c – bryanmac Dec 10 '11 at 02:09
  • http://stackoverflow.com/questions/1053592/objective-c-class-vs-instance-methods – bryanmac Dec 10 '11 at 02:10
  • (A class method is essentially the same as a "static method", though the Objective-C purists will scream that there's no resemblance.) – Hot Licks Dec 10 '11 at 02:11
  • a singleton has a class or static method which always returns the same instance of the object - usually with some synchronization for thread safety. – bryanmac Dec 10 '11 at 02:11
  • Ok I see the answer I need below then. Thanks all. – Ethan Allen Dec 10 '11 at 02:12
  • As Hot Licks pointed out a static C# function is *similar* to a class method. As for the C# singleton, see the possible duplicate I linked. – bryanmac Dec 10 '11 at 02:14

2 Answers2

1

Here is the closest thing to your code in C# (it is not exactly the same, because in Objective-C you can "override" static methods, but in C# you cannot).

class MyClass {
    static public void MyMethod() {
        // Do something
    }
}

public class Program {
    public static void Main(string[] args) {
        MyClass.MyMethod();
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

I don't really understand from this debate what you really need. Here is the singleton pattern in C#:

public class MyClass
{
    private static MyClass instance;

    private MyClass()
    {
    }

    public static GetInstance()
    {
        if(instance == null)
            instance = new MyClass();
        return instance;
    }
}
Tudor
  • 61,523
  • 12
  • 102
  • 142