Click here to Skip to main content
14,239,593 members
Rate this:
Please Sign up or sign in to vote.
See more:
i want to create object of class as public. mns whn we use oops concept in asp.net that time we need to create object of that class in each page bt i want create only once and it can be accessible to all pages.
Posted
Comments
Sandeep Mewara 1-Oct-12 2:55am
   
Care to elaborate your thinking and design?

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Hi,

You can use the concept of Singleton pattern.

Refer the link http://msdn.microsoft.com/en-us/library/ff650316.aspx[^] for implementing singleton pattern.

You can also make your class static and then when you call member of that class first time the object of that class will be created and the same object will be used through out the project.

Example with Static class.
public static class A
{
  public static int RunMyMethod()
  {
    //int intvar=0;
    //some code
    //return intvar;
  }
}

public class YourPageClass
{
  int result = A.RunMyMethod(); //Here you dont need to write new for creating the obj of static class A it will create object of the class A internally and the same instance will be used through out the project.
}

But my suggestion is to use Singleton pattern to create single instance of the class.

Example of Singleton pattern from MSDN.
public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

By using this calass you will make sure only one instance of the class will be crated and used through out the project.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100