Structs in C# 10 or What brings a structure’s explicit parameterless constructor?

Guriy Samarin
3 min readDec 15, 2021

--

TLDR: Is struct design faulted and needs to be fixed? And does an explicit parameterless constructor fixes some of the design flaws? No. And no. And no. But no one forces you to use structs, right?

It seems like structures don't get enough love in .Net (I am certainly not a fan). But recently they got the new feature and this triggers the discussions. The question is why sometimes an explicit parameterless constructor (EPC) gets called and in different cases, it gets ignored. Like if you write var arr = new A[2] given we have EPC — the constructor doesn't get called. According to the language specification, it’s easy: every array member is initialized by assigning default to it (no matter struct or class we are talking about). The problem is the state of the defaulted value type is somehow half-backed. It’s not null it’s something. And trying to access defaulted value type won't cause an easy-to-spot error. Was EPC a chance to finally make struct right and fix this behavior?

Actually, the idea came about C# 6 and was removed from release because of issues (the discussion in this thread contains a lot of reasoning about the way of “fixing” value type). And EPC was always supported in IL, so it was purely C# language constraint. So it’s not a new feature for IL. And to make structures right, we need to agree upon struts being wrong in the first place. It seems like calling constructor is not too big an overhead, but I definitely prefer to do it manually. And performance might suffer otherwise (Jon Skeet on the matter).

The structs handling is not so trivial as it seems (f.i. read Eric Lippert Debunking another myth about value types). And low-level parts are heavily dependent on this handling. If you are not in the Interop scenario or in need of counting every byte and nanosecond — you are better off. Structs (especially mutable ones) bring more problems for the average programmer than solve.

Update:

There is an interesting development in this feature. Using net SDK under 6.0.100 you can do something like that:

struct S
{
public int Value = 42;
}

But it is illegal since 6.0.200. It seems like this could change in future. But for now it’s not so convenient to use.

References:

--

--

Guriy Samarin
Guriy Samarin

Written by Guriy Samarin

Software developer at Amazon. Web (mostly backend) development now. My stack — .NET (APS.NET Core MVC).

No responses yet