I have a semi generic class that receives a Func<> from another class to tell it how to convert data. In a somewhat stripped down fashion, the code it looks like:
public class A
{
public B b;
public void init()
{
b = new B(ConvertRawData);
}
public double ConvertRawData(double rawData)
{
if(rawData == 1023)
RaiseMalfunctionEvent();
return rawData;
}
public void CalculateData(double rawData)
{
b.CalculateData(rawData);
}
}
public class B
{
event EventHandler Malfunction;
Func<double, double> _converter;
public B(Func<double, double> converter)
{
_converter = converter;
}
public void CalculateData(rawData)
{
var myVal = _converter(rawData);
}
}
What I am wanting to do is be able to raise an event in the Func<> but be able to handle that event in class B. Right now the event is actually raised in class A.
So my question is how can I make class B without exposing a public event handler in class B? Or is this even possible?
Edit
As far as it being an event instead of an exception. This is external data from a sensor. The sensor sends 1023 to indicate it is in an error state, so I need to flag the data and notify the user, but would it really be an exception in my program?
I agree with others, this looks like the best approach is to use exceptions: Create a new exception class
ComnversionMalfunctionException, throw it in your delegate and then catch it inCalculateData(). In the catch clause, you can then raise the event.But if you don’t want to use exceptions, you can do this by passing a delegate to the
converterdelegate that raises the event: