Its possible to have a C++ static_assert equivalent on dotnet? #80826
Unanswered
gustavopsantos
asked this question in
Ideas
Replies: 1 comment
-
In C#, some compile-time assertions can be done with hacks like this (SharpLab): class C {
public const int I = 69;
public int Member { get; }
}
static class A {
// Do not call at run time.
static void StaticAssertions(C instance) {
// Assert that C.I is 42.
_ = new byte[C.I == 42 ? 1 : -1];
// Assert that the type of C.Member is long.
var m = instance.Member;
StaticAssertType<long>(ref m);
}
static void StaticAssertType<T>(ref T value) {}
} If the assertions fail, the compiler errors do not outright say so:
A unit test, or perhaps a Roslyn analyzer, could give better diagnostics. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I would like to know, from compiler perspective, its possible to have assertions that runs before code gets compiled?
It can be very useful to do some safe guards.
Beta Was this translation helpful? Give feedback.
All reactions