Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does newing an empty struct do in C#?

Tags:

c#

clr

struct

If you have declared a struct:

struct EmptyResult
{
}

What is the result of creating a variable of type EmptyResult in an instance?

public Foo()
{
    EmptyResult result;
}

Would you expect an allocation on the stack, or is it effectively a no-op?

like image 757
Paul Turner Avatar asked Jun 06 '13 15:06

Paul Turner


1 Answers

A C# struct with no fields still has a size of 1. The reason this is so is that the compiler must be able to take the address of a struct using the & operator in unsafe code.

I would expect your struct type to be treated exactly the same way as the byte type.

like image 72
David Heffernan Avatar answered Sep 28 '22 06:09

David Heffernan