user10425264
user10425264

Reputation:

C# Singleton design pattern basics

Just recently started to try and learn some designs patterns. Currently trying to get my singleton to return a new object. However it keeps throwing the error "Cannot convert method group 'getInstance' to non-delegate type 'MainWdinow.CustomerLoader'. did you intend to invoke the method?

here is the code for the design pattern method

  public class CustomerLoader
    {
        private static Customer firstInstance = null;
        public static Customer getInstance()
        {
            if(firstInstance ==null)
            {
                firstInstance = new Customer();
            }

            return firstInstance;
        }
    }

Here is where I try to call the method and I get the error mentioned above

CustomerLoader t = CustomerLoader.getInstance();

I want my singleton to do the job of the code below and create a new instance of the customer object

Customer T = new Customer;

Upvotes: 0

Views: 691

Answers (3)

Wanton
Wanton

Reputation: 840

Use this. It's also thread safe unlike your version

private static readonly Lazy<Customer> _instance = new Lazy<Customer>(() => new Customer());
public static Customer Instance => _instance.Value;

But you should really use dependency injection instead singletons.

And your naming is off, it looks like Java, check this https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members

private members are not covered by guidelines. But even Microsoft uses _camelCase for private fields in corefx https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/coding-style.md

Upvotes: 2

Madzina
Madzina

Reputation: 1

CustomerLoader.getInstance

Is a function, you cant assign it to CustomerLoader

Your code should look more like that:

class Train
{
    protected Train() { }

    protected static Train instance;

    public static Train GetSingeltonInstance()
    {
        if(instance == null)
        {
            instance = new Train();
        }

        return instance;
    }
}

class TainUser
{
    private readonly Train train;
    public TainUser()
    {
        train = Train.GetSingeltonInstance();
    }
}

Upvotes: -1

mkdavor
mkdavor

Reputation: 134

Use this example:

public class Singleton    
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

Singleton()
{
}

public static Singleton Instance
{
    get
    {
        lock (padlock)
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}
}
  1. Singleton should be about one class, not three.
  2. Be careful with it cause your implementation is not thread-safe. See this padlock variable here. It prevents creating multiple instances in a multi-treaded applicatoins.

Upvotes: 0

Related Questions