Abdelfattah Radwan
Abdelfattah Radwan

Reputation: 475

Out Parameters or Callbacks?

If I have a class like this...

public class Singleton
{
    public static Singleton Instance { get; private set; }
}

And it has these two methods...

public static bool TryGetInstance(out Singleton instance)
{
    return (instance = Singleton.instance) != null;
}

public static void GetInstance(Action<Singleton> callback)
{
    if (instance != null)
    {
        callback?.Invoke(instance);
    }
}

One of them as you can see assigns a value to the out parameter and returns a bool and it can be used like this...

if (Singleton.TryGetInstance(out Singleton singleton))
{
    // Do something with singleton...
}

And the other checks if the instance of singleton is not null and executes a callback and can be used like this...

Singleton.GetInstance((singleton) => { /* Do something with singleton */ });

Is there's any real benefit if I use one over the other? Is there's any performance gains/losses?

Upvotes: 0

Views: 94

Answers (2)

Christoph L&#252;tjen
Christoph L&#252;tjen

Reputation: 5804

I'd ignore the performance question (callback may be a little bit slower and allocate), but look how you would use it:

 // You just want to call a function if instance is available?
 Singleton.Instance?.MyFn()

 // You want to do some setup stuff that may fail
 if(Singleton.TryGet(out i)) {
   // do stuff if instance available
 }

 // You want async logic during instance setup
 Singleton.GetInstance(i => {
    // do stuff when instance is available
 });
 // alternative
 var i = await Singleton.GetInstanceAsync();

So the question is: What do you need? (async? can setup fail? ...) and that dictates how much complexity you have to accept when accessing your instance.

If setup of your instance should never fail, simply ensure it's never null and you don't have to check for null everywhere...

 static readonly Singleton Instance = new Singleton();

Pls. note that I've ignored thread safety.

Upvotes: 1

Jasper Kent
Jasper Kent

Reputation: 3676

Hard to see why you'd use either. It's an odd variant of the Singleton pattern to have a variant where the Singleton is not available.

However, if this is what you want, why not just return null when there is no Singleton?

The Try...(out Thing x) is only really necessary when Thing is a value type.

Upvotes: 1

Related Questions