A
Alun Harford
I've recently been playing with TypedReferences (basically type-safe
pointers).
You can't have a field of type TypedReference because it would make
garbage collection really hard (the garbage collector would need to work
out that you're holding on to a TypedReference to a variable within a
struct but not the struct itself).
For the same reason, you can't cast a TypedReference to an object.
So I wondered what would happen if I used one in a closure.
public class Program
{
public struct Foo
{
public int A { get; set; }
}
public static void Main(string[] args)
{
Foo foo = new Foo();
TypedReference tr = __makeref(foo.A);
Action a = () => Console.WriteLine( __refvalue(tr, int));
}
}
Bang! On VS2008 it crashes the compiler, and on VS2005 it crashes the
whole IDE. This shouldn't come as too much of a surprise: I can't think
of a way this could possibly be compiled into IL. I think all the
compiler could really do is to produce an error message instead of crashing.
It looks like the MS implementation of the CLR isn't quite compatible
with MS C#.
The .NET framework uses TypedReferences internally, so the challenge is:
Can you figure out a less clearly silly way of getting this bug to
appear? Ideally without explicitly using TypedReferences?
Alun Harford
pointers).
You can't have a field of type TypedReference because it would make
garbage collection really hard (the garbage collector would need to work
out that you're holding on to a TypedReference to a variable within a
struct but not the struct itself).
For the same reason, you can't cast a TypedReference to an object.
So I wondered what would happen if I used one in a closure.
public class Program
{
public struct Foo
{
public int A { get; set; }
}
public static void Main(string[] args)
{
Foo foo = new Foo();
TypedReference tr = __makeref(foo.A);
Action a = () => Console.WriteLine( __refvalue(tr, int));
}
}
Bang! On VS2008 it crashes the compiler, and on VS2005 it crashes the
whole IDE. This shouldn't come as too much of a surprise: I can't think
of a way this could possibly be compiled into IL. I think all the
compiler could really do is to produce an error message instead of crashing.
It looks like the MS implementation of the CLR isn't quite compatible
with MS C#.
The .NET framework uses TypedReferences internally, so the challenge is:
Can you figure out a less clearly silly way of getting this bug to
appear? Ideally without explicitly using TypedReferences?
Alun Harford