aGentLuLz aGentLuLz - 3 months ago 8
C# Question

Is there a cleaner alternative to using events within this code?

Hi first of sorry if the question is not worded brilliantly.
And for the question, Is there a better way to achieve the following:

public class UntouchableClass
{
public event GetStringValue GetTestString;
public delegate string GetStringValue(string id, EventArgs e);

private string myValue;

public void SimulateWork()
{
myValue = GetTestString.Invoke("ResultFromSimulatedWork", null);
}
public string WhatDidIAssign()
{
return myValue;
}
}


and then it is used like this

private void button2_Click(object sender, EventArgs e)
{
UntouchableClass classy = new UntouchableClass();
classy.GetTestString += (s, ev) =>
{
return "RandomValue from " + s;
};
classy.SimulateWork();
MessageBox.Show(classy.WhatDidIAssign());
}


I am simply asking for better alternatives, if you could point me in a direction or show an example of something, I would appreciate it.

Answer

You could rewrite it like this, using delegates:

public void SimulateWork(Func<string, string> myFunc)
{
    if (myFunc != null)
    {
        myValue = myFunc("ResultFromSimulatedWork");
    }
}

The call to it would look like:

classy.SimulateWork(i => "RandomValue from " + i);
Comments