473,657 Members | 2,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dealing with Null Values

I'm getting increasingly frustrated with C# and its exceptions on null
values. Rather than try to deal with it on a hit-or-miss basis as
exceptions pop up, I thought I should try to learn exactly how C# deals
with null. Of course, there's nothing obvious in the docs like "Dealing
with Null Values" and a search on "null" yielded 500 results, most of
which don't apply. Can anybody point me in the right direction? Or offer
some general guidelines? Or even the correct keyword to search the docs?

sandman

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #1
20 4041
Max Sandman <sa*********@ya hoo.com> wrote:
I'm getting increasingly frustrated with C# and its exceptions on null
values. Rather than try to deal with it on a hit-or-miss basis as
exceptions pop up, I thought I should try to learn exactly how C# deals
with null. Of course, there's nothing obvious in the docs like "Dealing
with Null Values" and a search on "null" yielded 500 results, most of
which don't apply. Can anybody point me in the right direction? Or offer
some general guidelines? Or even the correct keyword to search the docs?


Never try to dereference null - that's when you'll get an exception.

Read the documentation for methods you call - they should (but probably
won't always, unfortunately) specify whether or not null is a valid
value for the parameters you pass in, and whether or not the method may
return null.

Basically, make sure you know at all times which of your variables may
be null, and what it means for them to be null. Then don't dereference
those null values :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #2
Hi Max,
Well I think that you will not find what you are looking for, now the
question to ask is why you are getting so much null values in your program,
are you sure you initialize all your variables correctly? are you checking
for null before using a object, it's non uncommon method returning null when
a value is not found like this example:

DataRow row = dataset.Tables["table1"].Rows.Find( pk );
//I have to check if row is a valid row or null
if ( row != null ) { .... }
Other than that, I do not what to advise you.

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Max Sandman" <sa*********@ya hoo.com> wrote in message
news:uE******** ******@TK2MSFTN GP09.phx.gbl...
I'm getting increasingly frustrated with C# and its exceptions on null
values. Rather than try to deal with it on a hit-or-miss basis as
exceptions pop up, I thought I should try to learn exactly how C# deals
with null. Of course, there's nothing obvious in the docs like "Dealing
with Null Values" and a search on "null" yielded 500 results, most of
which don't apply. Can anybody point me in the right direction? Or offer
some general guidelines? Or even the correct keyword to search the docs?

sandman

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #3
JS
with respect to Nulls...what are your frustrations?
examples?
-----Original Message-----
I'm getting increasingly frustrated with C# and its exceptions on nullvalues. Rather than try to deal with it on a hit-or- miss basis asexceptions pop up, I thought I should try to learn exactly how C# dealswith null. Of course, there's nothing obvious in the docs like "Dealingwith Null Values" and a search on "null" yielded 500 results, most ofwhich don't apply. Can anybody point me in the right direction? Or offersome general guidelines? Or even the correct keyword to search the docs?
sandman

*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
.

Nov 15 '05 #4
there's a null object pattern too, which is sometimes appropriate to save
explicit tests for null
http://c2.com/cgi/wiki?NullObject
"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.com...
Max Sandman <sa*********@ya hoo.com> wrote:
I'm getting increasingly frustrated with C# and its exceptions on null
values. Rather than try to deal with it on a hit-or-miss basis as
exceptions pop up, I thought I should try to learn exactly how C# deals
with null. Of course, there's nothing obvious in the docs like "Dealing
with Null Values" and a search on "null" yielded 500 results, most of
which don't apply. Can anybody point me in the right direction? Or offer
some general guidelines? Or even the correct keyword to search the docs?


Never try to dereference null - that's when you'll get an exception.

Read the documentation for methods you call - they should (but probably
won't always, unfortunately) specify whether or not null is a valid
value for the parameters you pass in, and whether or not the method may
return null.

Basically, make sure you know at all times which of your variables may
be null, and what it means for them to be null. Then don't dereference
those null values :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

Nov 15 '05 #5
Joe

"Max Sandman" <sa*********@ya hoo.com> wrote in message
news:uE******** ******@TK2MSFTN GP09.phx.gbl...
I'm getting increasingly frustrated with C# and its exceptions on null
values. Rather than try to deal with it on a hit-or-miss basis as
exceptions pop up, I thought I should try to learn exactly how C# deals
with null. Of course, there's nothing obvious in the docs like "Dealing
with Null Values" and a search on "null" yielded 500 results, most of
which don't apply. Can anybody point me in the right direction? Or offer
some general guidelines? Or even the correct keyword to search the docs?


Hi Max,

Off the top of my head, here are a few coding practices that I use to avoid
these types of problems:

1. Initialize variables so you always know they are in a valid state. If
you explicitly initialize them to null, you know that they start off in an
invalid state (anticipating that the algorithm should bring them to a valid
state) and you should check them before you use them.

2. Check for null before making library calls to 3rd pary libraries where
null is invalid.

3. Use Debug.Assert for pre and post-condition checking to make sure your
algorithms start and end in valid states. It's really easy to use for
pre-conditions, i.e. making sure input parameters are not null.

4. Get NUnit, http://nunit.org/, (or another unit testing tool that you
would prefer) and test positive and negative conditions. I use this all the
time and do regular regression tests that keep me out of trouble.

Joe
--
http://www.csharp-station.com
Nov 15 '05 #6
Joe <jo*@nospam.com > wrote:
3. Use Debug.Assert for pre and post-condition checking to make sure your
algorithms start and end in valid states. It's really easy to use for
pre-conditions, i.e. making sure input parameters are not null.


I would suggest not using Debug.Assert for that kind of thing - I'd use
a straight exception:

if (someParameter= =null)
throw new ArgumentNullExc eption ("someParameter ");

At least for non-private methods - it would make sense to use
assertions for private methods.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #7
Joe

"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.com...
Joe <jo*@nospam.com > wrote:
3. Use Debug.Assert for pre and post-condition checking to make sure your algorithms start and end in valid states. It's really easy to use for
pre-conditions, i.e. making sure input parameters are not null.


I would suggest not using Debug.Assert for that kind of thing - I'd use
a straight exception:

if (someParameter= =null)
throw new ArgumentNullExc eption ("someParameter ");

At least for non-private methods - it would make sense to use
assertions for private methods.


Actually, I do both. Maybe I'm afraid someone else on the team will eat the
exception and I want to make sure they don't overlook it. :)

Joe
--
http://www.csharp-station.com
Nov 15 '05 #8
I'm finding null to be a bit frustrating too. What am I missing?

Consider the following example...

object o = null;

System.String x = null;

o = null;

y y1=null;

if(o!=null)

{

Console.WriteLi ne(o.ToString() );

}

y is defined as follows:

class y

{

}

My frustration is that o is *never* null. I watch it in the debugger and
even the assignment makes it not null. Why?

System.String starts and null and happily stays that way.

What is going on?

Nov 15 '05 #9
ab***********@h otmail.com <ab***********@ hotmail.com> wrote:
I'm finding null to be a bit frustrating too. What am I missing?

Consider the following example...

object o = null;
System.String x = null;
o = null;
y y1=null;
if(o!=null)
{
Console.WriteLi ne(o.ToString() );
}

y is defined as follows:

class y
{
}

My frustration is that o is *never* null. I watch it in the debugger and
even the assignment makes it not null. Why?


I'm sure it's just the debugger being strange - o certainly *is* null.
Here's a program to demonstrate that, using bits of your code:

using System;

public class Test
{
static void Main()
{
object o = null;

System.String x = null;

o = null;

if(o!=null)
{
Console.WriteLi ne(o.ToString() );
}
else
{
Console.WriteLi ne ("o was null");
}
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
45408
by: Agoston Bejo | last post by:
I want to enforce such a constraint on a column that would ensure that the values be all unique, but this wouldn't apply to NULL values. (I.e. there may be more than one NULL value in the column.) How can I achieve this? I suppose I would get the most-hated "table/view is changing, trigger/function may not see it" error if I tried to write a trigger that checks the uniqueness of non-null values upon insert/update.
13
1843
by: Eric Lilja | last post by:
Hello, consider the following complete program: #include <assert.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> static int has_char(const char *, const char);
1
3622
by: Matt | last post by:
I could use some help dealing with null blobs. I'm returning a transaction from an Image BLOB field in SQL Server 2000 using C#. If the transaction exists the value is returned with out trouble, but because the ID can exist without having a value in the Image column the returned value is NULL and the code can't handle it and I receive this error when the Stored Procedure's value is returned (the line of code is marked with "**HERE**": ...
5
7783
by: Stephen Cawood | last post by:
I'm trying to use a C++ .lib from C# (I tried the Interop group will no results). I have a working wrapper DLL (I can get back simple things like int), but I'm having issues dealing with an array of bytes. For example, the .lib contains this function: int create(int id, int scale, unsigned char *image); In the wrapper DLL I have this function:
5
1979
by: BobRoyAce | last post by:
Let's say I have a table called Users which has a field DeptID which is an int. I also have a User class which has a method for getting the data for a particular user (i.e. User with specified ID) and which has a field that corresponds to the DeptID field and it is called _DeptID and is an Integer. Well, suppose that the value of the field in the database is NULL. In that case, I can't assign the value from the DB to the field. ...
3
11002
by: ineedahelp | last post by:
Can anyone tell me if this is correct code? I have to deal with an occasional NULL value in MarketPrice. I am cycling through a recordset created by an SQL If IsNull(rst!MarketPrice) Then....
17
1707
by: Christopher Benson-Manica | last post by:
Some recent posts got me thinking about how one might have dealt with simplistic malloc() implementations which might return NULL for a 64K request but might accept two 32K requests or four 16K requests. (I'm assuming, perhaps incorrectly, that quality modern implementations will coalesce free space as necessary and if possible to satisfy requests.) I came up with the following (compilable but untested) first cut at code to try a...
4
7720
by: Deckarep | last post by:
Hey everyone, Is there a more elegant or cleaner way of accomplishing the following null check? List<stringmyString = null; //Purposely null list of strings to show the example XElement element = new XElement("Strings",
0
2183
by: raylopez99 | last post by:
I ran afoul of this Compiler error CS1612 recently, when trying to modify a Point, which I had made have a property. It's pointless to do this (initially it will compile, but you'll run into problems later). Apparently Point is a struct, a value type, and it does not behave like a classic structure (in my mind's eye, and see below). Traditionally I think of a classic structure as simply an object where every member is public. But with...
0
8310
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8826
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7330
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6166
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.