MLBeast
MLBeast

Reputation: 13

C# - How to pass List<T> to a delegate as parameter

In essence what I am trying to do is I am creating a delegate that i want to pass the function to a method - that will take a List of Product Objects and will perform certain calculations.

Unfortunately I am getting an error message

main.cs(11,40): error CS0120: An object reference is required to access non-static member `MainClass.MyDelegate(System.Collections.Generic.List)' Compilation failed: 1 error(s), 0 warnings compiler exit status 1

My question is how come I am struggling to pass a list to a delegate - what am I doing wrong ?

Thank You and Kind Regards


using System;
using System.Collections.Generic;
using System.Collections;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine ("Hello World");
    MyCart MyBasket =  new MyCart();
    MyBasket.Initialize();
    //Console.WriteLine(MyBasket.basket.Count);
    MyBasket.BuyItem("Iphone", 300.3m, MyDelegate );
  }

  public void MyDelegate (List<Product> e){
    // this is where i am performing my delegate
    if (e.Count > 2)
    {
      Console.WriteLine($"This is delegate Talking our current Cart has more than 2 items inside, in fact the count is  {e.Count}");
    }
    else

    {
      Console.WriteLine($"This is delegate Talking our current Cart has less than 2 items inside, in fact the count is  {e.Count}");
    }
  }
}

public class MyCart
{
//public delegate void ObjectCheck(List<Product> basket) ;

public List<Product> basket = new List<Product>();
public delegate void ObjectCheck(List<Product> basket) ;
public void Initialize (){
  // this is our Cart Class constructor
  basket.Add(new Product { ItemName = "Book", ItemPrice = 4.9m });
  basket.Add(new Product { ItemName = "Milk", ItemPrice = 3.5m });
}

public void BuyItem (string i, decimal p, ObjectCheck mymethod)
{
  basket.Add(new Product {ItemName = i, ItemPrice = p});

  mymethod(basket);

}
}

Upvotes: 1

Views: 831

Answers (1)

nalka
nalka

Reputation: 2360

You're having this error because MyDelegate is an instance method (doesn't have the static keyword on it) and it's being used on a static context (Main). To fix the error you need to declare MyDelegate this way :

public static void MyDelegate (List<Product> e)
{
    // do some stuff
}

Upvotes: 1

Related Questions