David Reis David Reis - 2 months ago 7
C# Question

Casting Action<string> to Action<object>

I need to cast an

. 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.Action
1[System.String]' to type 'System.Action

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

I created a new question at http://stackoverflow.com/questions/4085798/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


I know your post specifies that wrapping in another delegate is not an option but unfortunately that's really your best choice here. The CLR simply does not allow for a cast between delegates in this direction. No amount of reflection can fix this either. Can you elaborate further on why this is not an option?

The reason why is that it creates type safety issues because the caller can pass any object into the Action<object> while the Action<string> can only handle strings. Even if your code only passes in a string the CLR cannot guarantee this and hence does not allow for the unsafe conversion.

The next best option I can think of is change the original method which is being wrapped in a Action<string> from taking a parameter of type string to one that takes object. Then let it manually verify the type is string. For example

// Original Version
void Method(string str) {
  // Operate on the string

// Modified version
void Method(object obj) { 
  string str = (string)obj;
  // operate on the string