Does the compiler discard empty methods?

Would C# compiler optimize empty void methods away? Something like

private void DoNothing()
{
}

As essentially, no code is run aside from adding DoNothing to the call stack and removing it again, wouldn't it be better to optimize this call away?

Jon Skeet
people
quotationmark

Would C# compiler optimize empty void methods away?

No. They could still be accessed via reflection, so it's important that the method itself stays.

Any call sites are likely to include the call as well - but the JIT may optimize them away. It's in a much better position to do so. It's basically a special case of inlining, where the inlined code is empty.

Note that if you call it on another object:

foo.DoNothing();

that's not a no-op, because it will check that foo is non-null.

people

See more on this question at Stackoverflow