简体   繁体   中英

Why does the compiler remove unused structs but not classes

I have the fallowing code

static void Main(string[] args)
{
    var str = new DummyStruct();
    var testClass = new DummyClass();
}

Neither the class or the struct have any implementation. But when I look at the code after a release build using ILSpy I get

private static void Main(string[] args)
{
    new DummyClass();
}

So my question is: Why does the compiler ignore the instantiation of a struct but not the one of a class ?

var str = new DummyStruct(); , when str is subsequently unused, doesn't do anything. In particular, no constructor of DummyStruct gets called.

var testClass = new DummyClass(); , when testClass is subsequently unused, does potentially do something. The constructor of DummyClass may have side effects. Even if it doesn't currently have side effects as far as the compiler can see, if it resides in a different assembly, it may have side effects at run time if a different version of the library is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM