简体   繁体   中英

Why does my compiler allow new() calls on structs?

I'm running VS 2017, targeting .NET 4.6.1, C# 6.0.

public struct Foo{}

My compiler is allowing Foo bar = new Foo();

My compiler is also allowing double d = new double();

EDIT: For clarification, I'm referring to calling a parameterless constructor. Aren't parameterless constructors for structs disallowed?

The new operator in C# is multi-purpose, and used on both classes and structs to create new instances. It is independent of the implementation details of either.

Under the covers, C# turns the new into the IL op named newobj . newobj knows at runtime what kind of type it is dealing with and the particulars of how to allocate memory for it.

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