Lyrk Lyrk - 1 month ago 6
C# Question

Event can't be raised

I am trying to do an assignment given but I am failing to do so. I wrote a product class and made a flower from it. Then I want to raise an event when flower quantity falls below 20, It should give me a warning. I think I am having difficulty in raising the event. I am sure I made the declerations of delegate and event correct but something is missing. Thank you in advance.

This line

flower.StockDecreased();


gives me this error:

Error 3 The event 'StokTakip.Product.StockDecreased' can only appear on the left hand side of += or -= (except when used from within the type 'StokTakip.Product')


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

namespace StokTakip
{
class Program
{
static void FlowerStockDecreased()
{
Console.WriteLine("Flower stock decreased");
}

static void Main(string[] args)
{
Product flower = new Product("Flower", 50);
Console.WriteLine(flower);

flower.StockDecreased += new Product.FlowerEventHandler(FlowerStockDecreased);

while (true)
{
Console.WriteLine("What is your choice");
Console.WriteLine("[1] Stock entry quantity ");
Console.WriteLine("[2] Stock exit quantity: ");

int choice = Convert.ToInt32(Console.ReadLine());

if (choice == 1)
{
Console.Write("Enter stock entry quantity: ");
flower.quantity += Convert.ToInt32(Console.ReadLine());

}

else if (choice == 2)
{
Console.Write("Enter stock exit quantity: ");
flower.quantity -= Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine(flower);

if (flower.quantity<20)
{
flower.StockDecreased(); //????

}
}
}
}


}

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

namespace StokTakip
{
public class Product
{
public string name;
public int quantity;

public Product(string a, int m)
{
name = a;
quantity = m;
}

public override string ToString()
{
return "Name: "+ this.name + " Stock Quantity: " + this.quantity;
}

public delegate void FlowerEventHandler();
public event FlowerEventHandler StockDecreased;
}


}

Answer

The error message is pretty clear. You can not raise an event like that. Only the declaring class can call the event like this and thus raise the event. All other classes can only add (+=) or remove (-=) event handlers from the event.

What you can do is put a public method into the Product class that raises the event like this:

public void RaiseStockDecreased()
{
    if (StockDecreased != null)
        StockDecreased();
}

You could call that externally.

But then again, this contradicts proper design, as I'd expect the Product class itself to determine whether stock was increased or decreased and raise the proper events. Otherwise you have to implement that logic in every place you want to be notified about stock changes.