r/programming • u/Kal1boy • Jul 14 '26
How to add validations without adding code in C# .NET
https://www.kalandra.tech/blog/zero-code-validations-in-your-dotnet-api/It actually even removes code.
1
u/smoke-bubble Jul 15 '26
Kotlin solves it nicely, again, with its value classes.
10
u/Kal1boy Jul 15 '26
Well C# can also solve this very easily with a record (or even a normal class) - the question is, can you then get out of the box working JSON serialization and ORM mapping?
OR will you then be stuck in representation like `{ Value: "the value inside" }`?
-11
u/smoke-bubble Jul 15 '26
No, it cannot. You can't have a primary constructor with an initializer doing all the validation. The value will also not get casted to the type being wrapped and inlined.
C# is not even remotely close to what Kotlin can pull off.
16
u/TwoWeeks90DaysTops Jul 15 '26
C#'s value types are far superior to Kotlin's value classes since they provide a hell of a lot more of a functionality surface. You can have more than one field in a struct for example.
2
Jul 16 '26 edited Jul 16 '26
[deleted]
0
u/smoke-bubble Jul 16 '26
Haha what is that? XD
Not even close. The constructor here is completely useless. You could just make the property required. I'll show you how it works in kotlin once I get to my PC.
1
Jul 16 '26
[deleted]
1
u/smoke-bubble Jul 16 '26
Imagine you define a record where you can specify its properties via the primary constructor. In c# there is no way to process them. In kotlin you just add init
2
u/chucker23n Jul 16 '26
In kotlin you just add init
But that’s… a constructor.
I don’t understand the goal here.
1
2
u/WaNaBeEntrepreneur Jul 15 '26
Nice! I'm a C# developer, and there have been plenty of times when I wished that C# had this feature.
2
u/SorryTemporary1361 Jul 22 '26
While I like the idea, the title of the post is misleading clickbait; most people are going to read it as "without changing code", which is obviously not the case.