-2

Why set it to null first ?

[EDIT]

there was this code about reading some file..it was like

StreamReader sr=null;
StreamReader sr= new StreamReader("file.txt");

I asked why would you set "SR" as null first BEFORE referencing the file u wanna read

Serenity
  • 4,968
  • 19
  • 65
  • 104
  • 1
    You really should provide an example of what you are talking about. Otherwise, this question is about as vague as it gets. – sgriffinusa Sep 24 '10 at 05:38
  • I am talking about StreamReader here ? – Serenity Sep 24 '10 at 05:47
  • 1
    And that comment is going to help? – Dykam Sep 24 '10 at 05:49
  • You state that there is a "need" to set StreamReader to null. There is no such requirement. What is making you think this? Are you getting errors in your code, a colleague is telling you, etc. We need more information if we are to assist. – sgriffinusa Sep 24 '10 at 05:49
  • have added details..hope that helps now :/ – Serenity Sep 24 '10 at 05:51
  • I thot it must be common practice to set that pointer to null first..so asked in a general way..sry.."sr" is a pointer right ?? – Serenity Sep 24 '10 at 05:56
  • ok great now its closed..I editted it ! :( – Serenity Sep 24 '10 at 05:58
  • Close but what for downvote?? – abatishchev Sep 24 '10 at 05:59
  • @user: Tim's answer below should serve you. There is no need to set a StreamReader to null before constructing it. – Michael Petrotta Sep 24 '10 at 05:59
  • In situations where you have a try/catch/finally (example: http://stackoverflow.com/questions/16352879/write-list-of-objects-to-a-file#answer-22416929 ), you would put the sr.Close(); in the finally block, and in such a case you need to set sr to null or to something, else you will get an error in VisualStudio. – Jo Smo May 08 '14 at 13:39

1 Answers1

8

There is no need to do that... in fact, the code above should give you a compile error as sr is already defined.

And you should probably write it as

using (var sr = new StreamReader("file.txt"))
{
        //code here
}

in order to make sure it is properly disposed after usage (lookup IDisposable)

TimothyP
  • 21,178
  • 26
  • 94
  • 142