Click here to Skip to main content
15,898,987 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

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.
C#
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.
C#
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.
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900