G
Guest
When I run the following code I would suspect a null reference exception to
be thrown:
param1 = null;
int x = param1.Length;
However, when I compile this code dynamically into a class and method a null
reference exception is ONLY thrown if the debugger is attached???? Otherwise
no exception is thrown. Can someone please explain this? I included the
code below - create a console application and overwrite the existing class
with the code below.
CODE TO REPRODUCE:
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Assembly a = CreateAssembly();
object o = a.CreateInstance("ConsoleApplication1.TestClass");
MethodInfo info = o.GetType().GetMethod("RunMe");
info.Invoke(o, new object[] { null });
}
private static Assembly CreateAssembly()
{
string src = @"
namespace ConsoleApplication1
{
using System;
public class TestClass
{
public virtual void RunMe(string param1)
{
int x = param1.Length;
}
}
}";
CodeDomProvider provider = new CSharpCodeProvider();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.IncludeDebugInformation = false;
compilerParameters.GenerateExecutable = false;
CompilerResults results =
provider.CompileAssemblyFromSource(compilerParameters,
src);
return results.CompiledAssembly;
}
}
}
be thrown:
param1 = null;
int x = param1.Length;
However, when I compile this code dynamically into a class and method a null
reference exception is ONLY thrown if the debugger is attached???? Otherwise
no exception is thrown. Can someone please explain this? I included the
code below - create a console application and overwrite the existing class
with the code below.
CODE TO REPRODUCE:
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Assembly a = CreateAssembly();
object o = a.CreateInstance("ConsoleApplication1.TestClass");
MethodInfo info = o.GetType().GetMethod("RunMe");
info.Invoke(o, new object[] { null });
}
private static Assembly CreateAssembly()
{
string src = @"
namespace ConsoleApplication1
{
using System;
public class TestClass
{
public virtual void RunMe(string param1)
{
int x = param1.Length;
}
}
}";
CodeDomProvider provider = new CSharpCodeProvider();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.IncludeDebugInformation = false;
compilerParameters.GenerateExecutable = false;
CompilerResults results =
provider.CompileAssemblyFromSource(compilerParameters,
src);
return results.CompiledAssembly;
}
}
}