Confusion Over Structs

I was recently perusing an article called C# developer interview questions and answers. I do a lot of interviews of developers with C# experience; so, I like to see what others think are good questions. The article was generally good, but there was this…


Good question. Good first sentence. Then things start to go down-hill.

First let’s look at the claim that “Structs are passed by value and not by reference.” This is technically true, but betrays a superficial understanding of the language. In C#, all parameters are are passed by value. It just so happens that the value of a reference type is in fact a reference. If that doesn’t make sense, read this article by Jon Skeet. A better way to state the point would be: “Structs are value types, while classes are reference types.” This would also cover the part about not being able to inherit from structs because all value types are sealed.

Next we have “Structs are stored on the stack not heap.” This is false. Look at this code:


Where will the Point inside the Shape be stored? Clearly on the heap. It is true that value types declared as local variables, even though they may be newed up, are still allocated on the executing thread’s stack space…


Now we get to the best of all… “The result is better performance with Structs.” If it were that simple we would always use structs and wouldn’t even need classes. The reality is that some objects are better modeled as classes and some are better modeled as structs. Discussing what kinds of objects are best modeled as structs would be a great question.

Leave a Reply

Your email address will not be published. Required fields are marked *