Search code examples
c#asp.net-mvc-3partial-classes

Can partial class access static methods in C#?


The tutorial application, MusicStore -MVC3 (92 PageNo), created a POCO class like:

public partial class ShoppingCart
    {
        MusicStoreEntities storeDB = new MusicStoreEntities();

        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }
     }

How can we access static method in partial classes? In my opinion, we cannot access static methods in a partial class. The partial attribute means other parts of the class will be included in the namespace. In this scenario, I do not know where this other partial class is implemented.

My questions about this static method are:

  1. Can we access static methods in partial classes? If so, how?
  2. Where is this partial class implemented in this MusicStore application? I am not able to find the other part of this class's implementation.

Updated: There is no other ShoppingCart class in the models directory. Does anyone know where that partial implementation would be?


Solution

  • A partial class in C# can definitely access static methods. The partial attribute simply says a class can (not must) be defined accross multiple files and otherwise doesn't affect member lookup.

    EDIT Responding to comment in question

    A possible explanation for why you can't find the other implementation of ShoppingCart is it may not exist. A partial class is not required to have multiple definitions. The partial only means there may be other parts of the definition.