Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing void to a generic class

I'm trying to create a form that will animate something while processing a particular task (passed as a delegate to the constructor). It's working fine, but the problem I'm having is that I can't instantiate a copy of my generic class if the particular method that I want to perform has a return type of void.

I understand that this is by design and all, but I'm wondering if there is a known workaround for situations like this.

If it helps at all my windows form looks like so (trimmed for brevity):

public partial class operatingWindow<T> : Form
{
    public delegate T Operation();
    private Operation m_Operation;

    private T m_ReturnValue;
    public T ValueReturned { get { return m_ReturnValue; } }

    public operatingWindow(Operation operation) { /*...*/ }
}

And I call it like:

operatingWindow<int> processing = new operatingWindow<int>(new operatingWindow<int>.Operation(this.doStuff));
processing.ShowDialog();

// ... 
private int doStuff()
{
    Thread.Sleep(3000);

    return 0;
}
like image 801
Steven Evers Avatar asked Mar 20 '09 23:03

Steven Evers


People also ask

Can generic be void?

Currently, void is not allowed as a generic parameter for a type or a method, what makes it hard in some cases to implement a common logic for a method, that's why we have Task and Task<T> for instance.

Can generic class be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

Can a non-generic class have a generic method?

Yes, you can define a generic method in a non-generic class in Java.

How do you restrict a generic class?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.


1 Answers

No, you'll need to create an overload to do that.

e.g.

public operatingWindow(Action action) 
{ 
    m_Operation=() => { action(); return null; }
}

Also you don't need to define your own delegate, you can use Func<T> and Action.

like image 187
laktak Avatar answered Sep 21 '22 16:09

laktak