Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Action<string> to Action<object>

Tags:

c#

delegates

I need to cast an Action<string> to Action<object>. While this is type-unsafe in general, in my case it will always be called with a string. I'm getting this error:

Unable to cast object of type 'System.Action1[System.String]' to type 'System.Action1[System.Object]'.

Any clues? Reflection is fair game. Wrapping the one delegate into another is not.

UPDATE: I created a new question at Creating an performant open delegate for an property setter or getter with a better explanation of my issue, and a solution using wrapping which I want to improve on

like image 576
David Reis Avatar asked Dec 01 '25 17:12

David Reis


1 Answers

First, it's not safe. Something that can accept any string can't (necessarily) accept any object. Think of a example method:

void method(String s)
{
  s.Trim();
}

Obviously, this would fail if s were an object without Trim.

Technically, this means Action is contravariant on T. You could assign an Action<string> to a hypothetical Action<SubclassString> reference, but string can not be subclassed.

It's true that C# allows regular unsafe casts (e.g. object itself to string), at the risk of a InvalidCastException. However, they chose not to implement the infrastructure for unsafe delegate casts.

EDIT: I don't know of a way to do it without a wrapper.

like image 91
Matthew Flaschen Avatar answered Dec 03 '25 09:12

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!