I would like to have a delegate that is constrained to returning one of two types; an ActionResult or a string. Is this possible?
No, it's not possible (at least not in C# 4 and below). There's no support for "or" constraints on generic type parameters.
There's also no constraint that restricts a type argument to be an exact type. All constraints restrict the base types of the type argument. They cannot restrict you from inheriting from them.
No, it's not. Besides, what would be the benefit of doing this? Unless the two types have something in common, then there's nothing that you can really do with the return type.
Consider some code that calls the delegate:
var returnValue = someDelegate();
What type is var
in this case? The only common ancestor of string
and ActionResult
is object
, so that's all you can get from it. From a static typing point of view, you may as well just declare the return type as object
.
Like Zakalwe, I also don't see any point in doing this, but..
You could define two overloaded methods which accept a Func<string>
and a Func<ActionResult>
respectively. A private method could take Delegate and do further things with it.
As other answers have explained, you cannot do this, however you could work around it by passing different continutations for each return type:
public delegate void MultiPathDelegate(Action<ActionResult> arAction, Action<string> strAction);
So checking the return type occurs in the delegate instead of the caller.