Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a static object from inside its own class

Tags:

c#

oop

static

Hi I have some code where I use a static object of Manager to call methods from Manager:

public class Manager
{
    public static Manager sManager = new Manager();
    public int x;

    public Manager()
    {  
    }


    public void Modify()
    {
        x ++;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Manager.sManager.x);
        Manager.sManager.Modify();
        Console.WriteLine(Manager.sManager.x);
        Console.ReadLine();
    }
}

Is this a good way of accessing a method from Manager from outside or is there a better way if the class Manager must own the method Modify.

Would use of events in this case be a better way to build this and have Manager listen for an update?

Or is there a better way to handle this even if I want the method Modify to stay inside the Manager class?

like image 404
azuric Avatar asked Feb 07 '26 12:02

azuric


2 Answers

It depends on the architecture you're trying to build.

Make everything static

If it's as simple as that, just make x and Modify static and you won't need an instance.

Use a singleton pattern

If you do need a Manager instance your code would be better using a Singleton pattern

private static Manager _manager;

public static Manager Manager
{
   get 
   {
      if (_manager == null)
      {
         _manager = new Manager();
      }
      return instance;
   }
}
like image 152
hardkoded Avatar answered Feb 09 '26 01:02

hardkoded


There is no reason here to create a static field of same type in the Manager class. You just need to create an object and then call the needed methods.

A more better way can be to make field private and just expose it for reading so that it can't be modified directly, and we only modify it by calling the modify() method:

public class Manager
{

  private int x;

  public int X
  {
    get
    {
       return x;
    }
  }

  public Manager()
  {  
  }


  public void Modify()
  {
      x++;
  }
} 

and then in your Program class use it:

class Program
{
    static void Main(string[] args)
    {
        Manager objManager = new  Manager();
        Console.WriteLine(objManager.X);

        objManager.Modify();

        Console.WriteLine(objManager.X);
        Console.ReadLine();
    }
}
like image 30
Ehsan Sajjad Avatar answered Feb 09 '26 01:02

Ehsan Sajjad