I recently came across on such piece of code (here is simplified version, which I checked and it works):
using System;
using System.Threading;
namespace Rextester
{
public class Program
{
public class Foo
{
public Foo()
{
thread = new Thread(new ThreadStart(Loop));
}
private void Loop()
{
}
private Thread thread;
}
public static void Main(string[] args)
{
var foo = new Foo();
Console.WriteLine("How does it work??");
}
}
}
Why does such code work without any complains from compiler? As I understand, Thread should start from function which should be static. (or reference to object and member function should be passed anyway). But here I see only passing reference to member function. It seems like I missed big thing in c#. May be there is implicit way of passing this reference?
UPD: great thanks. I just want to add minor addition of this fact. It turns out that compiler automatically handles delegates (passes correct reference object and method). here is il code:
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 32 (0x20)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: nop
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: ldftn instance void Rextester.Program/Foo::Loop()
IL_0010: newobj instance void
[mscorlib]System.Threading.ThreadStart::.ctor(object,
native int)
IL_0015: newobj instance void
[mscorlib]System.Threading.Thread::.ctor(class
[mscorlib]System.Threading.ThreadStart)
IL_001a: stfld class [mscorlib]System.Threading.Thread
Rextester.Program/Foo::thread
IL_001f: ret
} // end of method Foo::.ctor