Solved

Having trouble understand how static constructors work.

Posted on 2012-03-10
3
332 Views
Last Modified: 2012-03-11
Hi, I'm seeking an explanation of how constructors work in the following code. I believe that the static constructor would only ever be called once at the beginning of the program but if that's case then what is the point of "protected ShoppingCart( )". The other thing I find strange is "public static readonly ShoppingCart Instance", does that mean that you access the static object through the Instance data member?
using System.Collections.Generic;  
using System.Web;  
  
/** 
 * The ShoppingCart class 
 * 
 * Holds the items that are in the cart and provides methods for their manipulation 
 */  
public class ShoppingCart {  
    #region Properties  
  
    public List<CartItem> Items { get; private set; }  
 
    #endregion  
 
    #region Singleton Implementation  
  
    // Readonly properties can only be set in initialization or in a constructor  
    public static readonly ShoppingCart Instance;  
  
    // The static constructor is called as soon as the class is loaded into memory  
    static ShoppingCart() {  
        // If the cart is not in the session, create one and put it there  
        // Otherwise, get it from the session  
        if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) {  
            Instance = new ShoppingCart();  
            Instance.Items = new List<CartItem>();  
            HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;  
        } else {  
            Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];  
        }  
    }  
  
    // A protected constructor ensures that an object can't be created from outside  
    protected ShoppingCart() { }  
 
    #endregion  
 
    #region Item Modification Methods  
    /** 
     * AddItem() - Adds an item to the shopping 
     */  
    public void AddItem(int productId) {  
        // Create a new item to add to the cart  
        CartItem newItem = new CartItem(productId);  
  
        // If this item already exists in our list of items, increase the quantity  
        // Otherwise, add the new item to the list  
        if (Items.Contains(newItem)) {  
            foreach (CartItem item in Items) {  
                if (item.Equals(newItem)) {  
                    item.Quantity++;  
                    return;  
                }  
            }  
        } else {  
            newItem.Quantity = 1;  
            Items.Add(newItem);  
        }  
    }  
  
    /** 
     * SetItemQuantity() - Changes the quantity of an item in the cart 
     */  
    public void SetItemQuantity(int productId, int quantity) {  
        // If we are setting the quantity to 0, remove the item entirely  
        if (quantity == 0) {  
            RemoveItem(productId);  
            return;  
        }  
  
        // Find the item and update the quantity  
        CartItem updatedItem = new CartItem(productId);  
  
        foreach (CartItem item in Items) {  
            if (item.Equals(updatedItem)) {  
                item.Quantity = quantity;  
                return;  
            }  
        }  
    }  
  
    /** 
     * RemoveItem() - Removes an item from the shopping cart 
     */  
    public void RemoveItem(int productId) {  
        CartItem removedItem = new CartItem(productId);  
        Items.Remove(removedItem);  
    }  
    #endregion  
 
    #region Reporting Methods  
    /** 
     * GetSubTotal() - returns the total price of all of the items 
     *                 before tax, shipping, etc. 
     */  
    public decimal GetSubTotal() {  
        decimal subTotal = 0;  
        foreach (CartItem item in Items)  
            subTotal += item.TotalPrice;  
  
        return subTotal;  
    }  
    #endregion  
}

Open in new window

0
Comment
Question by:Eindoofus
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 21

Expert Comment

by:Dale Burrell
ID: 37705939
Well all your questions are actually answered in the comments.

Its a singleton pattern, which means that within an application space only a single instance of this class will exist. http://en.wikipedia.org/wiki/Singleton_pattern (google for more).

As the comment says a protected constructor means you can't create an instance of the class outside the class, thus enforcing this instance as the only instance.

You last assumption is indeed correct, given you can't create an instance of the class you need to provide a method to access the single instance and that's done by exposing it as a property e.g.:

ShoppingCart.Instance.Method()/Property.
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 37706186
As the comment says a protected constructor means you can't create an instance of the class outside the class, thus enforcing this instance as the only instance.
Technically you can still create an instance from a derived class being that protected was used and the class is not sealed. All the singleton implementations I have seen have marked the non-static constructor as private.
0
 

Author Closing Comment

by:Eindoofus
ID: 37707358
I thought I was just misunderstanding how "protected" is used in this case. It's good to hear that most singletons would use "private" like I expected.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question