Home > Mobile >  Error CS1955: Non-invocable member 'ShoppingCartItem.GetTotal' cannot be used like a metho
Error CS1955: Non-invocable member 'ShoppingCartItem.GetTotal' cannot be used like a metho

Time:12-10

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CKK.Logic.Models
{
   public class ShoppingCartItem
   {
      private Product product;
      private int quantity;

      public ShoppingCartItem(Product aProduct, int aQuantity)
      {
         product = aProduct;
         quantity = aQuantity;
        
      }

     public Product GetProduct()
      {
         return product;
      }

      public void SetProduct(Product value)
      {
         product = value;
      }


      public int GetQuantity()
      {
         return quantity;
      }

      public void SetQuantity(int value)
      {
         quantity = value;
      }

      public decimal GetTotal { get; }


   }
      
   }

Error CS1955 Non-invocable member ShoppingCartItem.GetTotal cannot be used like a method.

This is the error I'm getting and I can't seem to get around this error I would greatly appreciate any help

CodePudding user response:

At some point in the code you haven't shown, you're trying to access the GetTotal property as if it were a method.

decimal total = item.GetTotal(); // Will not work

To access a property, omit the parentheses:

decimal total = item.GetTotal;

However, GetTotal is a poor choice of name for a property. I would suggest calling it Total instead.

Looking at your other methods, I'm guessing you're from a Java background? In C#, you would usually use properties instead of pairs of Get.../Set... methods:

public class ShoppingCartItem
{
    public ShoppingCartItem(Product product, int quantity)
    {
        Product = product;
        Quantity = quantity;
    }
    
    public Product Product { get; set; }
    public int Quantity { get; set; }
    public decimal Total { get; }
}

Properties - C# Programming Guide | Microsoft Docs

CodePudding user response:

When declaring getters and setters like this public decimal GetTotal { get; } in C# you are declaring a property, and not a method. So in this case you GetTotal is a property from which you can get the value like thisShoppingCartItem.GetTotal. As far as I can tell, GetTotal should not be a field but a method calculating the total.

I would rewrite your code like this:

public class ShoppingCartItem {
    private Product product {public get; public set; } //is it nessecary to have both public?
    private int quantity {public get; public set; }

    public ShoppingCartItem(Product aProduct, int aQuantity)
    {
        product = aProduct;
        quantity = aQuantity;
    }

    public decimal GetTotal {
        return product.price * quantity;
    }

}
  •  Tags:  
  • c#
  • Related