defining variable in loop

  • Thread starter Thread starter mp
  • Start date Start date
M

mp

if i need a variable that will contain different values as a loop progresses
do i define it outside of the loop and assign it inside? or does it not
matter
i see a lot of dotnet code that defines and assigns the variable at the same
time
but in a loop that may be creating mulitiple variables rather than re-using
one?
example 1
foreach (var fileInfo in fileQuery)
{
string fileName = fileInfo.Name;
}

or example 2

string fileName;

foreach (var fileInfo in fileQuery)
{fileName = fileInfo.Name;
}


also i don't understand why it's said strings are immutable,

from help; "String objects are immutable in that they cannot be changed once
created."

but it's not true

string s;

s="one thing"

s="somethign else"

?

thanks

mark
 
if i need a variable that will contain different values as a loop progresses
do i define it outside of the loop and assign it inside? or does it not
matter
i see a lot of dotnet code that defines and assigns the variable at the same
time
but in a loop that may be creating mulitiple variables rather than re-using
one?
example 1
foreach (var fileInfo in fileQuery)
{
string fileName = fileInfo.Name;
}

or example 2

string fileName;

foreach (var fileInfo in fileQuery)
{fileName = fileInfo.Name;
}

It is always a best practice to define the variable inside their usage
scope. If the fileName variable is only used inside the loop, then
define it inside. If it is used outside the loop, then define it outside.
also i don't understand why it's said strings are immutable,

from help; "String objects are immutable in that they cannot be changed once
created."

but it's not true

string s;

s="one thing"

s="somethign else"

On the above example, you're just changing reference. Consider below
example,

string str = "one thing";
str.Replace("thing", "sentence");
Console.WriteLine(str);

StringBuilder sb = new StringBuilder("one thing");
sb.Replace("thing", "sentence");
Console.WriteLine(sb);

See what the above code will output.

Regards.
 
kndg said:
It is always a best practice to define the variable inside their usage
scope. If the fileName variable is only used inside the loop, then define
it inside. If it is used outside the loop, then define it outside.


On the above example, you're just changing reference. Consider below
example,

string str = "one thing";
str.Replace("thing", "sentence");
Console.WriteLine(str);

StringBuilder sb = new StringBuilder("one thing");
sb.Replace("thing", "sentence");
Console.WriteLine(sb);

See what the above code will output.

Regards.

thanks for the info
mark
 
Back
Top