markzzz
markzzz

Reputation: 47947

Can I pass a generic class in a method?

I have many class called ErrorHandler, which does different things each. Every class is inside a namespace.

So:

namespace1.ErrorHandler
namespace2.ErrorHandler
namespace3.ErrorHandler

refers to three different classes. I want to have a method with a generic ErrorHandler parameter; so due to the one I pass to that method, it use it.

Is it possible?

Upvotes: 0

Views: 89

Answers (4)

Tigran
Tigran

Reputation: 62248

you can do it with interface, say:

public class namespace1.ErrorHandler : IErrorHandler {
}    

public class namespace2.ErrorHandler : IErrorHandler {
}
....

and method that handles errors may look like this:

public void HandleError(IErrorHandler handler) {
}

so can use this like:

var erh1 = new namespace1.ErrorHandler();
var erh2 = new namespace2.ErrorHandler();

....
HandleError(erh1);
HandleError(erh2);

Upvotes: 9

liquidsnake786
liquidsnake786

Reputation: 447

Allow the different classes to extend the same interface for example IErrorHandler and the the method that handles it will look like:

public void HandleError<T>(T errorHandler)
        where T: IErrorHandler
    {

    }

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65049

Have them all implement a common type.. class or interface:

interface IErrorHandler { }

class ErrorHandler : IErrorHandler {}

Then use that in your common method.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190897

With polymorphism, yes you can, as long as they derive from a common ErrorHandler type, either an interface or base class.

Upvotes: 1

Related Questions