Ankush Jain
Ankush Jain

Reputation: 7059

Can static properties return new instances of objects/classes in c#

I am building an application in ASP.NET MVC 4. I am creating a class (similar to Factory type) that will return me instance of my service classes which i have made in BAL Layer. I want to declare static properties in that class and they should return Instance of requested Service Class.

My question is that is it possible that a static propery will return instance of new class because static property will be allocated a memory that will remain throughout the application. I am little confused here, Please explain what happens and what is best way to do so.

Code done so far

public class Factory
{
    public static CountryService CountryServiceInstance
    {
        get
        {
            return new CountryService(new CountryRepository());
        }
    }
}

Upvotes: 1

Views: 3228

Answers (3)

kishore V M
kishore V M

Reputation: 811

your method CountryServiceInstance for each call will always gives you a new instance of CountryRepository.

As you have mentioned, Most of the Factory classes are static which are responsible for creating new object instances. If they give the same object instance none of the factory patterns will serve its intent.

you can undoubtedly proceed with your sinppet..

if you want to quickly validate you can check the created objects hashcode object.GetHashCode() they will be unique as they are separate objects

Upvotes: 1

George Vovos
George Vovos

Reputation: 7618

What you should do is write a function the will create the new instances not a get property

public class Factory
{
    public static CountryService CreateNewService()
    {
        return new CountryService(new CountryRepository());
    }
}

About your memory concern read Sriram Sakthivel's first comment
More about the Factory pattern here: http://msdn.microsoft.com/en-us/library/ee817667.aspx

Upvotes: 3

AgentFire
AgentFire

Reputation: 9780

A property in C# is just a method which returns what it should return in its body. In your case, each time you access that property, a new instance of the service will be created.

In case you want only one instance of that service, you might want to store it to the static private variable like this

private static readonly Lazy<CountryRepository> _fact 
    = new Lazy<CountryRepository>(() => new CountryRepository());

Also, a static properlty never stores something "in the memory throughout the application", but a programmer can do that.

Once again, a property is just a pair of set\get methods, unless you use an automatic property, where there is also a backing field created for the value to store.

A static keyword itself only specifies that a current class member must not be accessed though this keyword, and its value will be shared all across the appdomain (or your application).

Upvotes: 2

Related Questions