I’m doing a bunch of weird generic stuff which includes doing a lot of casts of delegate types, and for the most part it’s working perfectly.
However, I’m running into cast failure that I can’t find a reason for.
Here’s my method, and following debug data.
public static T GetInvokableDelegate<T>(string name) where T : class
{
return DelRegistry[name].GetSelectedMethod() as T;
//DelRegistry[name].GetSelectedMethod() returns System.Object,
//which may be any flavor of Func<> or Action<>
}
//These two pairs represent the values from the Debug view,
//of T and GetSelectedMethod() respectively
//This is when DelRegistry is returning the initial result from GetSelectedMethod(): This cast As T works fine.
//System.Action<string,AIDECore.Controller>
//{Method = {Void HAL_TestMethod(System.String, AIDECore.Controller)}}
//This is after the second call, GetSelectedMethod() is returning a different delegate, but with identical signature: This one fails
//System.Action<string,AIDECore.Controller>
//{Method = {Void HAL_TestMethod(System.String, AIDECore.Controller)}}
Inspecting the values at runtime shows that they appear to be identical. The specified cast works the first time, fails the second time.
Of note: it’s not the number of times it’s been called causing it to fail. In other test cases, I’ve added dozens of delegate versions to DelRegistry without problems.
My question is, can you get error output as to WHY an “As” cast fails? (Where failing means returning null)
Cast exception data:
[A]System.Action`2[System.String,AIDECore.Controller] cannot be cast to [B]System.Action`2[System.String,AIDECore.Controller].
Type A originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'.
Type B originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'.
So that basically says it can’t cast.
For the record, all versions returned from GetSelectedMethod() subsequent to the first, are from dynamically loaded Assemblies.
So why has this casting worked fine hundreds of times until now?
Delegate assignments are based on signature, but casts are not. So if in your second case the T delegate type is different the cast “failing” is expected behavior.
To convert delegate types, use code like this.
Edit: after reading your edit with the cast exception data, my bet is that your code somehow loads multiple different versions of the assembly holding the AIDECore.Controller type – check those types.