Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading