Soheil Alizadeh
Soheil Alizadeh

Reputation: 3066

Why are static methods not available in Singleton Instance?

I create generic type class of name SingletonGenerator<>. For implement Singelton Design Pattern. So, below code is it the class:

SingletonGenerator.cs

public class SingletonGenerator<T> where T : class, new()
{
    private static readonly Lazy<T> _instance =
      new Lazy<T>(() => new T(), LazyThreadSafetyMode.ExecutionAndPublication);

    private SingletonGenerator()
    {
    }

    public static T Instance => _instance.Value;
}

And, create other class for get instance:

AppDb.cs

public class AppDbContext
{
    public string Database { get; set; }
    private static string ConnectionString { get; set; }

    public static void Send()
    {
    }

    public void Go()
    {
    }
}

In Program.cs

class Program
{
    static void Main(string[] args)
    {
        var context = SingletonGenerator<AppDbContext>.Instance;

        var database = context.Database; // is available 
        var connection = context.ConnectionString; //is not available

        context.Go(); // is available 
        context.Send(); // is not available
    }
}

My Question is Why are static methods not available in Singleton Instance?

And My code is correct?

Upvotes: 0

Views: 509

Answers (3)

Roman
Roman

Reputation: 259

Well because they are static and belong to type (in your case AppDbContext) and not object instance, with singleton pattern you still create one instance even though the property for accessing it is static. So you can call them with type name

var connection = AppDbContext.ConnectionString;
AppDbContext.Send();

Upvotes: 1

YuvShap
YuvShap

Reputation: 3835

A static member cannot be referenced through an instance. Instead, it is referenced through the type name.

From the docs.

The problem has nothing to do with the fact your instance is a singleton, to reference a static member use the type name:

AppDbContext.Send();

Upvotes: 1

Guy
Guy

Reputation: 50809

For starters ConnectionString is private. You can't access it from another class.

You also can't accesses static method from an instance. You need to use the class

AppDbContext.ConnectionString;

AppDbContext.Send();

Upvotes: 1

Related Questions