aGentLuLz
aGentLuLz

Reputation: 3

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.

Upvotes: 0

Views: 227

Answers (3)

Xavier J
Xavier J

Reputation: 4634

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);

Upvotes: 0

Luaan
Luaan

Reputation: 63742

You shouldn't use event handlers that return a value, that's a big no-no.

Instead, use a simple delegate:

Func<string, string> getSomeString;

public string DoWork()
{
  return getSomeString?.Invoke(someArgument);
}

Depending on what exactly you're trying to do, you might want to pass the delegate either through the constructor of the class or directly as an argument to the DoWork method (string DoWork(Function<string, string> func)).

If you want to separate the work being done from the return value, you might want to consider using an async method that returns Task<string> instead of just string (or in your case, using a field that's read by a separate method). But again, this is pure guesswork on my part on what you're actually trying to achieve - your question isn't clear in that regard :)

Upvotes: 2

Elvinas J
Elvinas J

Reputation: 5

You could do the following:

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

And then use it as such:

MessageBox.Show(classy.SimulateWork());

Upvotes: 0

Related Questions