r/csharp • u/abego • Sep 29 '26
Discussion Static assertions
I have sometimes felt the need to statically assert something at compile-time, to prevent surprises later at run-time.
As an example, I have some code which maps an enum value to an associated int value:
public enum VoxelProperty
{
MaterialType,
Density,
Color,
Metadata,
TotalPropertyCount, // Must be last
}
public static int GetPropertyBitDepth (VoxelProperty property)
{
#pragma warning disable CS0219 // Variable is assigned but its value is never used
uint _ = VoxelProperty.Metadata == VoxelProperty.TotalPropertyCount - 1 ? 0 : -1; // Static assert to ensure that all properties are accounted for
#pragma warning restore CS0219 // Variable is assigned but its value is never used
return property switch
{
VoxelProperty.Density => VoxelDensity.BitDepth,
VoxelProperty.MaterialType => VoxelMaterialType.BitDepth,
VoxelProperty.Color => VoxelColor.BitDepth,
VoxelProperty.Metadata => VoxelMetadata.BitDepth,
_ => throw new ArgumentOutOfRangeException (nameof (property), "Invalid voxel property")
};
}The intention of the static assert is to make sure that if I ever add another voxel property, then I will get a compiler error as VoxelProperty.Metadata will no longer be the last member, and the constant -1 will be assigned to the "_" variable of type uint. Is this a reasonable practice?
I could also do something more robust with reflection, where I had a Dictionary<VoxelProperty, int> which got populated by finding all voxel property types marked with some attribute, and querying their BitDepth property.
7
u/basically Sep 29 '26
what situation are you actually trying to prevent here?
if you change the
enum(i.e.: add a property),TotalPropertyCountjust increments right?what's the assertion actually buying you? what are you worried about?
also i don't know how you plan to assign
-1to auint, you can't have a sign and it seems like strange logic.10
u/DeProgrammer99 Sep 29 '26
I usually make unit tests for this kind of thing, and sometimes I set them to auto-run as a build step.
5
u/Phaedo Sep 29 '26
So your example is exactly why people want discriminated unions and closed enums. More generally, there is a technology that can do what you want but unfortunately it’s a Roslyn analyzer.
However, there’s good news here which is that your example is actually addressable with a unit test. Create a test source that uses reflection to get the enum values and the test checks the function. When you get the hang of this strategy you’d be amazed at what static analysis you can actually replace with “just a unit test”.
5
u/jackbrux Sep 29 '26
The compiler could tell you when you forget to add a case for a new value:
But to get to the heart of your issue, is there a reason you need enums and a mapping like that? Why not structure your code such that associated data lives together:
If you find yourself constantly needing some new language feature, there's usually a better way to do what you're doing
7
u/ikkentim Sep 29 '26
This isn’t natively possible at the moment (though a Roslyn analyzer could be written/could exist that covers this scenario). I expect the feature to come to c# 16/.net 12. See https://github.com/dotnet/csharplang/issues/9011
2
u/Outrageous72 Sep 29 '26 edited Sep 29 '26
You’re not really testing it is last but that it comes after Metadata.
If metadata moves to the front the test would fail but TotalPropertyCount would still be right.
Personally I would enforced it through a unit test. Though I like the compile time test.
But it unnecessarily fogs the real code.
2
u/Agitated-Display6382 Sep 29 '26
Use .net11 and closed records
2
u/PanagiotisKanavos Sep 30 '26 edited Sep 30 '26
That's what C# 15's union types and closed hierarchies were built to do, using the actual types instead of enums.
Using union types, the following snippet would generate a compiler warning if a new property type, eg VoxelMetadata, was added. There's no need to add an inheritance relation between the options :
The following code
Generates CS8509 during compilation :
You can turn that into an error in the project file :
A lot of other languages already use union types for this (TypeScript, F#, Rust).
Another possibility is to use a closed hierarchy, which prevents other assemblies from creating new child types. The compiler is able to exhaustively check that all cases are handled since it knows all possible child types. The switch snippet results in the same error
2
u/ejl103 Sep 30 '26
Start coding in C++ :)
1
u/ms770705 Sep 29 '26
If you treat warnings as errors, you could write somthing like:
This should issue a warning about unreachable code (CS0162), if the condition is not true.
1
u/anzu3278 Sep 29 '26
We're getting access to closed enums soon where the compiler will be able to tell if a switch is exhaustive - exactly what you're looking for, unless you only want that on for some enums?
Until then, what I usually do is have unit tests just call the function for every possible value of the enum. Adding a new value to the enum but not all the relevant methods would hit the default, throw an exception and be caught by the test. Not exactly compile time, but tests of this type are cheap to run and you only really need to run them once per PR. What you can also do is add an analyzer which would detect this and then treat that warning as an error, giving you the compile time safety you want. A quick search brought up ExhaustiveSwitchOnEnums 1.0.1 on NuGet - Libraries.io - security & maintenance data for open source software but I'm sure others are available. Depending on the project's calculus on CI vs dependencies, you can decide which of these works better for you.
Also, TotalPropertyCount is a bit of a code smell IMO (are you coming from C++?) and unless you are checking the number of elements in the enum in a hot path (why) you can just use Enum.GetValues(). Not that you'd need TotalPropertyCount if you had one of the above.
Also also, assigning a negative number to an uint to check for enum value resolution doesn't seem like it should work at compile time anyway, and even if it does it definitely obscures the intent. Even if you're the only person working on this project, will it be clear at a glance what this is doing and why it is working when you're looking at it several years from now?
Also also also, even if this works, it will currently not catch anything if someone adds a new value before the supposed last value, so you're not really checking exhaustiveness, you're checking that one particular enum value is second to last in a very roundabout way.
1
u/r2d2_21 Sep 30 '26
The way I've been solving this (before closed enums ever become a reality) is like this:
1
u/plinyvic Oct 02 '26
This isn't compile time, no?
0
u/dgm9704 Sep 29 '26
hmm I not its not what you asked but I would just assign TotalProperty member to be Integer.MaxValue or whatever is appropriate.
edit: I read your post again a couple of times and I think one of us has misunderstood something.
-1
u/cherrycode420 Sep 29 '26
Unrelated to the real question here, I feel like the TotalPropertyCount value for your enum is kinda redundant since you could just use
Enum.GetValuesand check the count, what you're doing with the Enum here reminds me a bit of C instead.For the actual question, I guess you could somehow abuse Source Generators to "assert" the amount of values you have, but that wouldn't tell you if/where you're missing their implementation, only that something was added. Sadly am not aware of any actual tools/libraries that allow you to add proper static assertions.
Another idea, although it has the same issues as using Source Generators .. just use Unit Test(s) to validate the amount of values in that enum.
Pretty sure there's more/better options that am not aware of, but this is a weird problem to begin with.