0

I´m trying to do the following:

I have a class with a virtual method like this:

public virtual Event<T> Execute<T>(T message)

And that´s what I want:

Event T can be different of T message. For example: sometimes I need a function like this:

public override Event<Bitmap> Execute(string message)

But of course, I get the following error "no suitable method found to override".

Is there any way to do this? Use 2 types of generic objects using this override?

Note: I can change the virtual method, but the other classes always have to inherit this one.

Thank you!

3 Answers 3

2

You don't need to override it, override is used to change a method inherited from another class. If i understood correctly you want to overload this method, omit override and type virtual instead.

public virtual Event<Bitmap> Execute(string message)

When you will call this function the compiler will choose most appropriate method in dependence of what number/types of values you have passed to the method.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Thank you Adrian, guess that´s what I want!!
2

It sounds like you should move the generic type to the class or an interface and then implement/extend the Execute method:

public interface IExecutor<T>
{
    Event<T> Execute();
}

public class BitmapExecutor : IExecutor<Bitmap>
{
    Event<Bitmap> Execute() { ... }
}

It doesn't make sense to have an Execute<T> method, since that implies that it is valid for any supplied type T, rather than specific ones.

1 Comment

That´s a good idea! Thank you Lee! I will check the most proper solution using your answer =))
1

You could declare another overload for your method like this:

public virtual Event<K> Execute<T>(T message)

1 Comment

You can do that, but the syntax is wrong. You need to specific both types and those types will be unrelated, so you cannot work with them unless you do some runtime typecasting, removing advantage of generic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.