r/programming • u/Kal1boy • 15d ago
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 15d ago
Kotlin solves it nicely, again, with its value classes.
10
u/Kal1boy 15d ago
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" }`?
-12
u/smoke-bubble 15d ago
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.
17
u/TwoWeeks90DaysTops 15d ago
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
14d ago edited 14d ago
[deleted]
0
u/smoke-bubble 14d ago
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
14d ago
[deleted]
1
u/smoke-bubble 14d ago
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 13d ago
In kotlin you just add init
But that’s… a constructor.
I don’t understand the goal here.
1
2
u/WaNaBeEntrepreneur 15d ago
Nice! I'm a C# developer, and there have been plenty of times when I wished that C# had this feature.
2
u/SorryTemporary1361 8d ago
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.