Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a class global to the entire application?

Tags:

c#

.net

I would like to access a class everywhere in my application, how can I do this?

To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just include("abc.php") in both... I do not want to create the object everytime I want to use the code.

like image 586
Pokus Avatar asked Oct 08 '08 23:10

Pokus


People also ask

How do I create a global class in C#?

However, you can make a global variable by creating a static class in a separate class file in your application. First, create a class called global in your application with the code given below. The class also has a static variable. Now, you can access it from anywhere in your forms after assigning a value to it.

What is a static method in C#?

A static method in C# is a method that keeps only one copy of the method at the Type level, not the object level. That means, all instances of the class share the same copy of the method and its data.


2 Answers

Do you want to access the class or access an instance of the class from everywhere?

You can either make it a static class - public static class MyClass { } - or you can use the Singleton Pattern.

For the singleton pattern in its simplest form you can simply add a static property to the class (or some other class) that returns the same instance of the class like this:

public class MyClass
{
     private static MyClass myClass;

     public static MyClass MyClass
     {
          get { return myClass ?? (myClass = new MyClass()); }
     }

     private MyClass()
     {
          //private constructor makes it where this class can only be created by itself
     }
}
like image 192
Max Schmeling Avatar answered Sep 27 '22 20:09

Max Schmeling


The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (Concrete instance or Static access to that class)

Or

You can have a Singleton class to use it everywhere but some people won't recommend you this way to proceed.

like image 34
Patrick Desjardins Avatar answered Sep 27 '22 20:09

Patrick Desjardins