defining variable in loop

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
 
K

kndg

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.
 
M

mp

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
 

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