Click here to Skip to main content
15,881,804 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Instead of creating new object everytime i want to use already existing created object for accessing in C#

What I have tried:

C#
Instead of creating new object everytime i want to use already existing created object for accessing in C#

C#
if (obj1== null)
			{
				obj1= new obj1();
			}
Posted
Updated 9-Nov-16 1:50am

Well, no one prevents you in doing that. If your variable holds a valid reference to an object then use it. On the other hand, if your variable holds just null then you have to create an instance of the class (using the proper syntax, of course).
 
Share this answer
 
It's a very common pattern called a singleton, where there is only ever one instance of an object created. Google "Singleton pattern", and you'll find lots of stuff about it, but the basic formula is what you have there.

C#
class MyClass {
    private MyClass();
    private static MyClass _instance = null;

    public static MyClass TheInstance {
        get {
            if (_instance == null)
                _instance = new MyClass();
            return _instance;
        }
    }
    ...
}

// Then when you want to use it:
MyClass.TheInstance.SomeMethod();
var value = MyClass.TheInstance.SomeProperty;
 
Share this answer
 
Comments
NManikantan912 9-Nov-16 11:15am    
i want to use same instances with content changing
Midi_Mick 9-Nov-16 11:23am    
So, you add properties and/or methods that change the content.
NManikantan912 10-Nov-16 1:54am    
for my requirement the constructor has one parameter

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