locked
When making the method static -- an object reference is required to access non-static field, method or property RRS feed

  • Question

  • User-780198206 posted

    an object reference is required to access non-static field, method or property

    When I make the GetCartId  static Visual Studio complains

        public class Uno
        {
            private readonly HttpContext context;
    
            public Uno()
            {
            }
    
            public Uno(HttpContext _context)
            {
                context = _context;
            }
            public static string GetCartId()
            {
                string cartId = "";
                var stringId = context.Session.GetString("cart");
                if(stringId == null)
                {
                    cartId = Guid.NewGuid().ToString();
                    stringId = cartId;
                }
                else if(stringId != null)
                {
                    cartId = stringId;
                }
                return cartId;
            }
        }
    

    Sunday, July 3, 2016 5:55 PM

Answers

  • User-158764254 posted

    When I make the GetCartId  static Visual Studio complains

    That is because in that static method GetCartId, you are trying to access a non static member named context.

    var stringId = context.Session.GetString("cart");

    you cannot access any of the classes non-static members from your static method.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 3, 2016 6:30 PM