I have created a string variable called line
with get; and set; in csharp.
After that I am using this variable to read a text file in a while loop like below.
using(StreamReader Reader = new StreamReader(pathtofile))
{
while((line = Reader.ReadLine()) != null)
{
//things to do with the line using regex expressions.
}
}
I understand that strings in csharp are immutable. So my doubt is each time the line is read, does a new string created resulting in a unique line variable which takes up a lot of memory. How to solve? I want the the variable to be created only once and the same variable to be used for each line without multiple line variables in memory. I don't know how to solve the problem. Would anyone try to explain the real scenario ? Thanks in advance.
If you are using get;
and set;
, then you are declaring a property, not a field (i.e. variable). Frankly, you should probably be declaring a local variable as string line;
inside your loop, but it's impossible to know for sure without a good, minimal, complete code example.
As far as the question at hand goes, no: reassigning a new value to the variable does not create a new variable. The variable's lifetime is dictated by how it's declared, not by how often you assign something to it.
As you read through the file, a new value (i.e. a string
reference) will be assigned to the variable for each line. This will overwrite the old value. Assuming no other variable retains a reference to the old value, then the string
object referenced by that value will eventually be discarded by the garbage collector.
It may or may not be discarded immediately. In general, the operation of the GC is transparent to your own code. It works behind the scenes to make sure your program isn't consuming more memory than it needs to, while also ensuring not too much time is spent trying to keep memory consumption to a minimum (i.e. by allowing the "garbage" to accumulate to a degree, rather than always trying to free everything right away, it uses less CPU time managing memory).
Which is all to say, no…the code you posted does not waste memory. Indeed, it's an idiomatic way to implement line-by-line reading of a text file specifically without wasting memory. Contrast to something like e.g. File.ReadAllLines()
or TextReader.ReadToEnd()
, which try to store the entire file contents in memory all at once.