You must Sign In to post a response.
  • Category: .NET

    C Sharp - private instance and public instance

    I have class named(productdetails) , in that i am implementing singleton DP, now the doubt is

    private static ShoppingCart ShoppingCartInstance;

    public static ShoppingCart GetShoppingCart()
    if (ShoppingCartInstance == null)
    ShoppingCartInstance = new Business.ShoppingCart();
    return ShoppingCartInstance;

    why i am making one private instance and public instance, instead of writing private instance i can write directly public instance.
    why i need this private instance.

  • #769757
    There are some cases where we don't want to use a public instance, for example if you want a singleton class. like If you are writing an assembly which is going to used by 3rd parties then there would be a number of internal classes that you only want created by your assembly and not to be instantiated by users of your assembly. so, that you better to go with private scope identifier.

    Simply if you don't want to allow the others to create instances, then keep the scope identifier as private within a limited scope. The practical application is the singleton pattern.

    B.Ramana Reddy

  • Sign In to post your comments