r/badcode • • Aug 12 '20

c# How do you null check?

Post image
697 Upvotes

21 comments sorted by

97

u/KernowRoger Aug 12 '20

This is weirdness of SQL server where it returns a special type called DbNull instead of the value null. What you actually need to do is "is DbNull" against the value.

49

u/RiddSann Aug 12 '20

I've only ever done == DBNull.Value and now I feel dumb

34

u/gameditz Aug 12 '20

Isn’t c# the greatest?

5

u/kbruen Aug 13 '20

More like SQL server.

1

u/gameditz Aug 13 '20

SQL server did no one wrong. I like it better than MySQL

4

u/KernowRoger Aug 13 '20

I don't think it really matters tbh. I think we can all agree ToString-ing the type is not the right way haha

3

u/Kotentopf Aug 13 '20

I always do dbValue is DBNull

87

u/gameditz Aug 12 '20

That hurts

38

u/ReduceHyperlinks Aug 12 '20

That dude has been coding for waaaay too many days in a row.

11

u/the_monkey_of_lies Aug 13 '20

In an empty row?

27

u/RavynousHunter Aug 13 '20

Oh god, the number of times I've been caught with my pants down using regular null instead of DBNull... I really wish that the connecting whatsis between .NET and the database would translate between the two automatically, because that's just annoying.

16

u/cordialgerm Aug 13 '20

Yeah System.DbNull is ridiculous

-2

u/[deleted] Aug 13 '20

Now, if they named it something half-reasonable, like "NullaryDb", I might at least get the design of what they're trying to do. Realistically though, I get tired of catering to the "billion dollar mistake".

2

u/[deleted] Aug 14 '20

Why am I getting downvoted?? Nullary objects are a popular and effective design pattern.

18

u/HTTP_404_NotFound bool isEven(int num) => num%2==0 Aug 12 '20

Technically, not a null check.

Normally a null check in .net can be either...

Value is null Or... Value == null

But, A dbnull is not actually null.

So, instead,

Isempty = Row[0].field == dbnull.value

22

u/MeatyLabia Aug 13 '20

or "is DbNull".

9

u/[deleted] Aug 12 '20

This guy must think hes coding in cb

1

u/transcriber_mu Nov 03 '20

Image Transcription: Code (C#)


bool temp = (string)line[3] == "On";
bool isRowEmpty = line[1].GetType().ToString() == "System.DBNull";

if (!isRowEmpty)

[The cursor is hovering over GetType() and a pop-up hint displays "Type object.GetType()"]


I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

0

u/[deleted] Aug 13 '20

[deleted]

2

u/noXi0uz Aug 13 '20

just put everything in enums and hardcode them there /s