When to use null

S

Steven Blair

Hi,

Here is a small example function. What I would like to know is when I
should be using null:

private bool MyTestFunc(string Message)
{
StreamWriter sw=null;
string str=null;

sw = new StreamWriter(FILE_PATH,true);

//Do some stuff with the SW
str = String.Format(@"{0}|{1}|",CLASS_NAME,message);
sw.WriteLine(str);
sw.Close();

//Not sure what to do here, but here is my guess
sw=null;
str=null;
//If I didnt set these to null, would that mean the
//The GC wouldnt clean these objects up?

return true;
}


Any help on this would be appreciated.

Regards,

Steven
 
J

Jon Skeet [C# MVP]

Steven Blair said:
Here is a small example function. What I would like to know is when I
should be using null:

See http://blogs.msdn.com/csharpfaq/archive/2004/03/26/97229.aspx

What you *should* do is close your writer in a more reliable manner.
I'd also recommend only declaring variables at the point of first use.
I'd have written your method as:

void MyTestFunc (string message)
{
using (StreamWriter sw = new StreamWriter(FilePath, true))
{
sw.WriteLine ("{0}|{1}|", ClassName, message);
}
}

Differences:

o Constants follow MS naming conventions
o Parameter name follows MS naming conventions
o No need for the temporary string variable - the version of
WriteLine I use does the formatting anyway
o The StreamWriter is closed by the automatic call to Dispose
o String literal is now normal, rather than verbatim (as it
doesn't need to be verbatim)
o No declaration before use
o No unnecessary assignment to null
o No return value - on error, an exception will be thrown

Note that it still isn't thread-safe. Whether or not that's important
to you, I don't know.
 
J

jhgjlk jkhg

Ok, point taking. I will change my code to match what you have demontsrated.
But one of the points I was trying to get across was the use of strings.

Another small example:

void MyFunc()
{
string tmp=null;

tmp="Not very useful, only for testing";

//Do something with tmp

tmp=null // Is this neccessary?
}

Regards,

Steven
 
J

jhgjlk jkhg

Sorry, last post is not needed now. Read the articel you supplied a link for
and that answers my secodn question :$

Regards,

Steven
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top