473,789 Members | 2,624 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to use null

Hi,

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

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

sw = new StreamWriter(FI LE_PATH,true);

//Do some stuff with the SW
str = String.Format(@ "{0}|{1}|",CLAS S_NAME,message) ;
sw.WriteLine(st r);
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
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
3 1772
Steven Blair <st**********@b tinternet.com> wrote:
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/arch.../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(Fi lePath, 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.

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

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Steven Blair <st**********@b tinternet.com> wrote:
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/arch.../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(Fi lePath, 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.

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

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

Regards,

Steven

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Steven Blair <st**********@b tinternet.com> wrote:
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/arch.../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(Fi lePath, 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.

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

Nov 16 '05 #4

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

Similar topics

0
2364
by: Soefara | last post by:
Dear Sirs, I am experiencing strange results when trying to optimize a LEFT JOIN on 3 tables using MySQL. Given 3 tables A, B, C such as the following: create table A ( uniqueId int not null default 0 auto_increment, a1 varchar(64) not null default '',
0
683
by: Jerry | last post by:
Below is ALL the code for all the databases... Here's the problem: I callup the aspx file in IE and the form comes up just fine. When I select a person to update, I get the subject error. Aparently, when I select a person, it's not selecting anyone and returning this error. Here's the full error: Description: An unhandled exception occurred during the execution of the
10
4591
by: Lyle Fairfield | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbaac11/html/acfctNZ_HV05186465.asp "If the value of the variant argument is Null, the Nz function returns the number zero or a zero-length string (always returns a zero-length string when used in a query expression)" **** How many records are there in FirstTable in which Product Is Null. SELECT COUNT(*) AS CountofNullProdcut
17
4534
by: Mark A | last post by:
DB2 8.2 for Linux, FP 10 (also performs the same on DB2 8.2 for Windoes, FP 11). Using the SAMPLE database, tables EMP and EMLOYEE. In the followng stored procedure, 2 NULL columns (COMM) are selected into 2 different SP variables and compared for equal. They are both NULL, but do not compare as equal. When the Not NULL columns (SALARY) are compared, they do compare as equal.
3
1606
by: Ricardo Vazquez | last post by:
Hi! I have a new problem with this SCENARIO I already described in a previous post: - PBX (a private telephone exchange or switch) - A Telephony Server Application running on computer "A" (it communicates with the PBX via IP) - An ASP.NET application (running on computer "A") for web clients of that telephony server (running on computer "B", "C", etc.)
11
3268
by: MikeT | last post by:
This may sound very elementary, but can you trap when your object is set to null within the object? I have created a class that registers an event from an object passed in the constructor. When my object is destroyed, I want my object to un-register this event. If I don't then the object would never be destroyed until the object I passed in the constructor is destroyed. I have implemented a Dispose(), Dispose(bool), and ~Finalize...
1
1505
by: barrathi | last post by:
Hi all i need one query help! for reporting purpose i wrote one query - follows select s.tran_empid as EmpId, e.M_EMPL_NAME as EmpName, p.PROJ_NAME as Project, t.TITL_NAME as Title,CASE WHEN s.tran_param='Project Level Key Initiatives' THEN round((sum(s.tran_revscore)/(s.tran_weightage/100))) END as PLKI,CASE WHEN s.tran_param='Quality' THEN round((sum(s.tran_revscore)/(s.tran_weightage/100))) END as Quality,CASE WHEN...
6
5169
by: =?Utf-8?B?U2hhd24gU2VzbmE=?= | last post by:
Greetings! I was researching AJAX to provide a solution to displaying status messages while a long process executed. I found several examples online and was able to use their code to get a quick application working. However, when attempting to implement the solution, the AJAX calls weren't updating the screen like the examples were and seemed not to fire until after the long running process had completed. I found the only real...
9
3811
by: Francois Grieu | last post by:
When running the following code under MinGW, I get realloc(p,0) returned NULL Is that a non-conformance? TIA, Francois Grieu #include <stdio.h> #include <stdlib.h>
0
9666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9511
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,...
1
7529
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
6769
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
5417
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...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4092
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3700
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
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.