tags:

views:

369

answers:

5

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.

+3  A: 

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.

Daok
A: 

Define access. Instantiate everywhere or have a single object of it in memory?

Paul Nathan
+1  A: 

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
     }
}
Max Schmeling
+1  A: 

The other answers that you've been given about using a static class or a singleton pattern are correct.

Please consider, however, the fact that doing so does compromise your ability to test. In general, if you can, prefer dependency injection over globally accessed classes. I know this isn't always possible (or practical).

Just on that, you should also look up the abstract factory pattern. It allows you to have a well known factory class that produces the actual instance of a class that you're using. To have a globally accessed logging class, for example, don't directly create a logging class. Instead, use a logging factory to create it for you and return an interface to a logging class. That way it's easier to swap in and out different logging classes.

Andrew
+2  A: 

Since you do not want to create the object every time and it sounds like you are talking about some sort of utility methods...

I suggest you use static methods in an assembly which you can reference where needed

Declan Shanaghy