Each time you import a type it is a different instance of TypeReference
So this
var typeReference1 = moduleDefinition.Import(typeof (Exception));
var typeReference2 = moduleDefinition.Import(typeof (Exception));
Debug.WriteLine(typeReference1 == typeReference2);
Will output false
.
So when you are doing the query
VariableType
may be an instance ofTypeReference
representingException
exceptionTypeReference
will be an instance ofTypeReference
representingException
But they are not the same reference and there is no built in equality checking on TypeReference
.
What you need to do is
var exceptionType = module.Import(typeof(Exception));
var exceptionVariable = method
.Body
.Variables
.First(x => x.VariableType.FullName == exceptionType.FullName);
Also remember you have to handle inherited exception types.
As a side not be careful using .Import(typeof (Exception))
. The reason is that it give you the Exception type of the current code, not the Exception type of the target assembly. For example you could be processing a WinRT assembly using a .net4 assembly. Importing the .net4 Exception type will probably give you some strange behavior.
So you are just as safe doing this
var exceptionVariable = method
.Body
.Variables
.First(x => x.VariableType.FullName == "System.Exception");