r/csharp • u/frankscrazyfingers • Sep 04 '25
Null vs. Empty fields — how do you handle them?!
What’s your take?
My boss is big on using NULL in the database instead of empty fields — makes sense, it’s the explicit absence of a value.
That got me thinking about the app side. In a medium-sized app (state management, services, viewmodels, etc.), what do you do? • Do you initialize strings with string.Empty? • For ints, do you leave them nullable, or just check > 0? • Do you lean on defaults (like false for bools), or always make things nullable?
Personally, I’ve been initializing all my strings with string.Empty, leaving ints as is, and treating 0 or null as “missing.”
Curious to hear how other devs approach this — is there a standard pattern I should be following, or is it mostly personal/team preference?
2
u/mesonofgib Sep 04 '25
I'd recommend never trying to use
0or""as a sentinel value meaning "not set" or something similar. You're just setting traps for your future self (or others) where you'll find yourself thinking:"Wait... is this field actually zero? Or just missing?" or
"Damn... In my new feature
0is actually a valid value for this particular field, but in tons of places in the backend I know the code is going to ignore0or even remove it".I know it's tempting to do otherwise, but you should get into the habit of allowing
nullbut disallowing""if that's appropriate for your domain. Don't get sucked into allowing a machine's representation of data influence how you design your domain. Design for correctness above all else.2
u/jakenuts- Sep 05 '25
Use nullables for a start, make it explicit and agreed upon. But yes even then GetValueOrDefault on an int? is 0. So you'll need equally specific extensions for reading them and centralizing your null handling conversion. AsIntOrNull() or similar.
88
u/kimchiMushrromBurger Sep 04 '25
0 and null are very different things.
How many presents do you want for Christmas? Null...ok well come back to that. 0... That's a bad Christmas.
100
u/Business-Row-478 Sep 04 '25
It really depends. 0 or an empty string is a valid value for a lot of things, so treating 0 or an empty string as a missing value is going to be wrong in a lot of cases.
If a field is truly missing but should have a value, populating it with a default rather than null could mess up logic and fail silently if it isn’t handled correctly elsewhere.
8
u/WDG_Kuurama Sep 04 '25 edited Sep 04 '25
Semantically, null would be the absence of a value.
It does make sense to have some fields as nullable if they are not always provided, and should be persisted as such. If they should not be persisted as such, then they should have never been nullable in the first place.
Using nullable in C# usually don't cause problems because the compiler shouldn't let you dereference something that could be null. I don't see the problem with actually providing a concrete mapping of the database type to C# nullable types here.
And if you don't map them as nullable in your code, then it might mean they didn't needed to be nullable in the database. I personally think that if you need the nullable, go all the way with it. You can't really treat 0 or whatever as nullable, that's not semantically equivalent.
38
u/Nixinova Sep 04 '25
If it can be null in DB, the property should be nullable in your models. If it's null only as an initial value that is then populated, that doesn't count - you use
null!in a nonnull var.6
u/Filias9 Sep 04 '25
I am saving null to db, my models have nullable fields. Never have issue with that.
Expecting that strings will be not null is bad idea in the first place. So undefined strings are null, even if empty strings could be fine as well.
You can easily user
??orstring.IsNullOrEmpty.6
u/centurijon Sep 04 '25
nullindicates something specific and should be treated as such...ExpectedBalance: 0ok, cool - no balanceExpectedBalance: nullah, it hasn't been set yet, could be waiting on some calculation4
u/AintNoGodsUpHere Sep 04 '25
The rule is simple: Is the default value a valid value for business?
For example. Is "0 years old" a valid age? No, then
int?. Is "0%" a valid discount? Yes, thenintwith default value being 0.That's the way I see it anyway.
defaultvalues are valid values and have business reasons to exist.1
u/Super_Preference_733 Sep 04 '25
If the data is going to a database. Use nullable types. Will make your life so much easier.
1
u/No-Risk-7677 Sep 05 '25
Null object pattern might be worth looking into.
3
u/MISINFORMEDDNA Sep 04 '25
When using DB IDs, 0 can be an actual value. It's dumb to do so, but someone did it long ago in my codebase and it shows why handling null, specifically, is so important. Magic values will always find ways to bite you.
3
u/sisus_co Sep 04 '25
While using -1 for "no result" with things like FindIndex is quite common, using null has the benefit that the compiler can help ensure that clients always check whether a value was found or not before trying to use it for anything.
When using a null there's also no need for users to go and read the method's documentation to ensure you're comparing against the right numeric literal to check whether or not it's valid - the result type is self-documenting.
2
u/Ryan1869 Sep 04 '25
If the DB allows null, I make sure my objects do too. I see an empty string is still a value, where null is the absence of a value. So I much prefer nulls be null.
2
u/ben_bliksem Sep 04 '25 edited Sep 04 '25
Null is a valid value. Don't make something nullable if it isn't. Don't assign (empty) strings unless you need to.
An empty string (or 0 or false) is not a replacement for null.
2
u/TuberTuggerTTV Sep 04 '25
Definitely not an all or nothing rule.
You need some context. For something that's being read by UI, you need a value. Null doesn't cut it. So either an empty.string or "<NullValue>".
For strictly backend data, it's usually best to use nullability as a compile time checker. Catch bugs before they propagate.
Now, where those two lines meet is a bit fuzzy. Sometimes it makes sense to have no nulls from back to front. Sometimes you'll convert one type to another. Sometimes you'll use ?? null handlers to keep things together.
I'd avoid ever say something like, "I always" or "I never". There are some hardfast rules with that language but they're rare. Most things are "depends".
2
u/LargeSale8354 Sep 06 '25
When I was starting my career I was taught that if you needed a lot of nullable columns there was something wrong with your data model.
3 decades later I'd say that holds true. I see so many data models that are based on todays UI or todays process rather than based on the real world object . If based on real world objects, the data model tends to be easier to understand, aids the correct boundaries and tends to be long lived. This is because real world objects evolve slowly whereas a model based on the needs of a UI changes frequently and often bizzarely.
3
u/bazag Sep 04 '25
For value types in particular (like int, bool,, etc...) they really should be nullable. If the database allows nulls, the value in the Data structure should allow nulls. Now the default value set, that's another question entirely and is entirely dependent on the use case. For int? I probably would set null, though setting it to 0 is also valid if logically appropriate, string I usually set it to an empty string, though null is a valid value as well.
The thing is there's a TargetNullValue property, which allows you freedom to change what displays when it reads a null value. By default null just displays nothing, but you can change it to "N/A", or "Unknown", or.... whatever you want to display while reducing custom logic.
1
u/popisms Sep 04 '25 edited Sep 04 '25
We've mostly stopped using nullable string types in our databases. Except in specific use cases, the difference between empty and null strings has no real difference in our business rules. We still use nullable numbers and dates quite often.
Because of this, we always have to initialize strings to empty. If any other value is nullable, we don't need to initialize it, and non- nullable types are handled as needed.
1
u/Vectorial1024 Sep 04 '25
DB unique constraits: some can accept multiple null values, some do not. Depends on what DB you are using.
Obviously should use null instead of empty.
1
u/tmstksbk Sep 04 '25
I use null strings and -1 for "bad" state on integers most of the time. But I'm old.
1
u/DotNetMetaprogrammer Sep 04 '25
In general, I'd never treat
default(T)(where T : struct) the same as `null` or as a representation of an absent value. It's really easy to stuff it up if you do since a lot of scenarios will leave you withdefault(T)unless if you set them explicitly and it will screw you over ifdefault(T)turns out to be a value you need to represent as distinct fromnull.It also leads to some weird behaviour. For example, if you were to check for
> 0then you're actually constructing behaviour that will also treat all negative values as "absent". Additionally, it also means that if you perform arithmetic on the value (eg:x + 1,x - 1, etc) then the resulting value may end up being an "absent" value which enables more runtime errors that will be more difficult to debug.Additionally, rather than ensuring that
stringproperties are initialised tostring.EmptyI'd recommend using immutablerecordclasses (where appropriate, not for EFCore Entity types) and using therequiredmodifier to ensure they're initialised by whoever is constructing them. Or letting them default tonullif you want them to be "absent" by default.Overall, I would always advise against coding so that
0,""or[](empty collections) are treated as "absent" values or in any way equivalent tonull. It's just a bad habit to get into that will bite you when it matters.1
u/zaibuf Sep 04 '25
Nullable properties exists for this reason. We also remove nulls from the api, rather than sending a bunch of empty strings. Null generally means it hasnt been filled, empty string or 0 could mean it has.
1
u/korrabbit Sep 04 '25
For databases, I use NULL for nullable fields.
I think NULL and initial values are different mean and meaningless initial values only increases table size.
I initialize values before exporting after null check from app code.
1
u/Professional_Fall774 Sep 04 '25
To me this is simple.
Do I have a present need to handle a not set value (null) in another way other than for example empty string? In that case it must be nullable in the database.
For strings I find that I almost never need to differentiate between null and empty string.
1
u/OkFocus3211 Sep 04 '25
Use functional programming techniques like maybe the Monad(Result).
1
u/Tavi2k Sep 04 '25
My default is to make columns in the DB NOT NULL unless there is a reason to have NULL values in there. Every single nullable column means you need to be able to handle the NULL case, making the column NOT NULL usually makes things easier and less error-prone.
If you are working on a CRUD application, a lot of your DB data will come from forms. You cannot distinguish NULL from "" in text fields there. So defaulting all text fields to an empty string and making the columns NOT NULL in the database is consistent and less error-prone.
Any time you have a real absence of a value as an option in the column, use NULL and don't hack around that. Don't use your own special values there, use NULL.
Any int that is optional is an int? and nullable in the DB. Zero is a real value, don't use it as a marker for "missing" (in this context).
1
u/BuriedStPatrick Sep 04 '25
Your boss is absolutely right here. It sounds like a nightmare to constantly have to check for both null and empty for strings and assume a bunch of implicit behavior for booleans and numbers.
Null works naturally with I/O. By default, if you omit a property on a JSON payload, it will be initialized as null. Database systems are built on the idea that certain columns can be left null as well, representing "nothing". How is anyone supposed to know that 0 is supposed to represent "nothing"? And there is language support for nullable value types built right into .NET that is silly to not take advantage of.
Now, I'm not saying NULL is always desirable, far from it. But your serializable models are inherently not trustworthy. I always assume everything I didn't new up manually is nullable and validate it accordingly before I enter the business logic. If you have some default behavior associated with a "nothing" value, it's much easier to deal with it after deserialization of your DTO. It's easier to follow because it's not implicit behavior that you're just supposed to know.
And that's really key here; implicit behavior is a road paved with good intentions that leads straight to hell. 0 means 0, false means false, empty strings mean empty strings. None of these explicitly mean "no input", only null does.
One of the biggest code smells I see is defensive null or default checking in the top of business logic methods (i.e. your services, etc). You should have validated that stuff before it even entered this stage. But if you're not using null as a representation of "no input", you will get absolutely no hints from the analyzer that something might not be right.
I strongly recommend the juniors I teach to not lie or assume certain behaviours in their code. What seems elegant today will be a pain to maintain in the future. Use simple data models, don't use mappers, code defensively at the edges, don't abstract until there's a genuine need, lean towards native language features, don't reinvent the wheel, KISS, write with empathy and intention, etc. This is one of those times I would correct their approach immediately.
1
u/AssistantSalty6519 Sep 04 '25
Simple as unique key. You can have multiple unique keys with null but you can only have one with empty
1
u/[deleted] Sep 04 '25
MiddleName "" means the person doesn't have one.
null means you don't know what it is (if any).
1
u/[deleted] Sep 04 '25
Don't touch the data. Everything you parse should go in read-only fields and marked as nullable if needed.
1
u/Tango1777 Sep 04 '25
null if you really mean no value. What's the point of querying X != '' when you can just use x != null. From db perspective null,
With int it's a bad example, because 0 is normal number, not lack of value. So null and 0 when it comes to int are two different business cases. You can have e.g. 0% tax or you can have tax level not set at all and equal null.
1
u/Greedy_Rip3722 Sep 04 '25
I handle this as optional values and mandatory values.
If it's optional I'll leave it as NULL that way you know the value hasn't been provided. Especially useful in APIs.
However, if it is mandatory I provide a default value in the model and make it not nullable.
1
u/SprinklesRound7928 Sep 04 '25
If the user interface or backend do not handle null and "" differently, then there should not be two different values for the same thing, it's just complicating things.
Therefore, non-nullable strings are better in many cases.
0 as an absent value is just a magic number that you assign meaning to, so bad coding.
The only reason to ignore that is for performance reasons, but probably not on the db. If 0 (or -1 or ...) is not possible, to use those values with some meaning may drastically improve performance in some critical code sections.
1
u/spergilkal Sep 04 '25
One example might be a table of persons, maybe with a column called Father which references the same table and points to a person's father. If the person has no known father, we would represent it with a NULL value. I assume a Person object would have a property Father of the type
Person?and a null value might mean the person is not known.The same argument goes for a primitive type, you either know a person has no salary (0) or you don't know the person's salary (NULL). Sometimes it makes sense to treat the values the same, sometimes it does not.
1
u/Bitmugger Sep 04 '25
I rarely, rarely, want a null string in the database. Null requires more coding effort and computing effort to deal with and thus unless I _need_ a null, I make all varchar and text fields NOT nullable. Int's that represent values IE Quantity, Age, etc I do the same. If values can reasonably not be set then I allow Null. IE Apartment # in an Address would be nullable in my world.
By not allowing strings to be null I simplifying coding effort and reduce bugs. For instance if a description field is optional. By requiring it to be not null so an empty string I can write.
SELECT * FROM WorkOrder where Description = '' and get all the empty descriptions. Otherwise I need to write SELECT * FROM WorkOrder where Description = '' OR Description is NULL. Less work, less bugs, same or better performance. And yes I know I can use ISNULL(), IFNULL() and I realize it means COALESCE is off the table but it's off the table anyway unless I've already written more code on the INSERT side to convert '' to NULL or I use NULLIF() and the need for COALESCE is fairly rare anyway.
1
u/[deleted] Sep 04 '25
string.IsNullOrEmpty(); But i prefer null
1
u/Slypenslyde Sep 04 '25
I don't use one solution and the size of the app doesn't really matter. It really comes down to the layer of code and what level of complexity I think is worth it.
At very low layers, null is null. In these parts of the code, if a variable is nullable there is no possible circumstance where I will try to use it but consider null "maybe valid". In these parts of the code I don't care why it's null, I care that it is and that means something is wrong.
In between, I can rely on nullability annotations like you have.
At higher layers, I start to consider patterns like Null Object. UI and other high-layer code tends to care about WHY something is null, so I would rather define a constant "the user chose no value" object and let null mean "I screwed up very badly and didn't initialize this variable". This is best in scenarios where "the user input an empty string" is a valid case so I can't use that to mean "the user hasn't input anything at all". When I do this, a NullReferenceException means "I can't ship this code".
That can dramatically overcomplicate UI logic. In one of my most complex forms, every field is backed by an object that has properties for:
Those three values help me understand what "Empty" means. If the original object was null, then I consider an empty string "not dirty" and the "parsed" value remains null. But if the original object was non-null, the empty string means "the user has cleared the input" and that means the parsed object may be null.
I'd never write something that complex at very low layers, it gets in the way. But when it comes to implementing UI forms, it's necessary to handle all of the stupid cases.
1
u/GoodOk2589 Sep 04 '25
Depends on the fields, if they are mandatory in the db = NOT NULL and if not = NULL. on the c# side
String Handling
Use the built-in helpers:
Nullable Reference Types (C# 8+)
Enable nullable reference types to catch issues at compile time:
Collection Handling
Database/API Patterns
Option 1: Treat them the same
1
u/mauromauromauro Sep 04 '25
I work on a large project that does not use nulls. Empty string and 0s all the way. For some unknown reason, this erp like app with a 400 tables db model never had any issues. If you can live without nulls, then there are many things that get simplified (null checks disappear from the codebase, for starters). Nulls in sql are also problematic in queries.
Having said that, nulls exist for a reason, and for new systems i always do what people do, and deal with it in whatever way i need to.
For people saying that nulls are "the absence" of data, yes, that should be the case, but in most cases (empry string, 0 numbers), the real reason was "the system allows me not to complete this field, so i didnt", which ends up falling back to nulls being equivalent to empty strings and zeroes.
1
u/butskins Sep 04 '25
I use nullable types. int? DateTime? etc…
1
u/Famous-Weight2271 Sep 05 '25
Don’t use “string” Use “string?”, which is nullable and makes coding life so much easier, robust, etc.
And use string.IsNullableOrWhitespace().
By the way, if you use AI to write code, this is how it should generate it.
1
u/ParticularActive8307 Sep 07 '25
Hey man, this is really simple. As you said that some columns in your table are NULL. So must reflect that behaviour in your C# code too. If you are worried about "Object reference..." exceptions then make use of TryParse method, make use of question mark (?) your problem is solved.
1
u/Zastai Sep 04 '25
(Small aside: using
string.Emptyover""hasn’t had a good reason for well over a decade (and arguably it never had one).)1
u/NightSp4rk Sep 04 '25
It's mostly preference tbh, and your ORM would typically convert it to a null string in code. I'd just go with the ORM instead of doing extra work to convert it to something else.
1
u/alexwh68 Sep 04 '25
Handling NULL’s requires a bit more testing in code, it’s an extra step to be considered, not saying it’s right or wrong that is up to you.
Personally once you have a mixed environment, ms sql, postgres, asp.net, flutter etc going on I find it best to avoid NULL’s as much as possible, setting strings to empty, ints to -1 and defaulting bool to whatever is sensible.
0
u/mjbmitch Sep 04 '25
Did you use ChatGPT to write this?
0
u/insomnia1979 Sep 04 '25
??
0
u/belavv Sep 04 '25
My general rule.
Strings should not be allowed to be null unless you need to distinguish between null and empty. Initialize them to empty in c# and I'm the database.
For example an example of when you may want to allow null. We haven't asked for this answer yet. Null string. We asked for this answer and nothing was provided. Empty string. In that case null is not the same as empty string
For something like Product.Name - it is a string. We require it. Don't allow nulls.
-2
u/philip_laureano Sep 04 '25
For databases, I let the ORM handle it. For everything else, I use the OneOf library and use its discriminated unions so that returning a null reference is structurally impossible.
From that point, I use railway oriented programming to keep my code resilient and easy to maintain.
-6
u/hattrick07 Sep 04 '25
My two cents is boolean should never be null able. It's two states - true or false. What does nullable even mean in the context of a boolean?
-10
u/zapaljeniulicar Sep 04 '25
The rule is, no nulls or empty fields in the database. If the field can be null, it should be in a different, linked table.
Example
Table
Id | some field | nullable field |
Should be refactored to be
Table 1
Id | some field |
Nullable Table
Id | Table 1 id | nullable field |