Re-initialize a variable or declare a new one?

In C #, is there an advantage or disadvantage to reinitializing a previously declared variable instead of declaring and initializing a new one? (Ignoring thoughts of man's conciseness and readability.)

For example, compare these two examples:

DataColumn col = new DataColumn();
col.ColumnName = "Subsite";
dataTable.Columns.Add(col);

col = new DataColumn(); // Re-use the "col" declaration.
col.ColumnName = "Library";
dataTable.Columns.Add(col);

vs

DataColumn col1 = new DataColumn();
col1.ColumnName = "Subsite";
gridDataTable.Columns.Add(col1);

DataColumn col2 = new DataColumn(); // Declare a new variable instead.
col2.ColumnName = "Library";
gridDataTable.Columns.Add(col2);

A similar example involving loops:

string str;
for (int i = 0; i < 100; i++)
{
    str = "This is string #" + i.ToString(); // Re-initialize the "str" variable.
    Console.WriteLine(str);
}

vs

for (int i = 0; i < 100; i++)
{
    string str = "This is string #" + i.ToString(); // Declare a new "str" each iteration.
    Console.WriteLine(str);
}

Edit: Thank you all for your answers. After reading them, I thought that I would expand my question a little:

Please correct me if I am wrong.

When I declare and initialize a reference type, such as System.String, I have a pointer to this object that exists on the stack, and the contents of the object that exists on the heap (accessible only through the pointer).

, "str", 100 String, . , , "str", String. "" , , , , .

, 100 100 String.

, , . , ; , , ? , , , , , 100 , .

, " - ", , .

+3
5

, - . , str for. for , , , . , .

, . , , . , , .

+6

, , . , - 99,9% . . - .

, , , . , ( , , ). , , , .

+1

, , , . , .

, , , "for", , . . , , , . , :

string test = "new string";
test = "and now I am reusing the string";

, :

string test1 = "new string";
string test2 = "and now I am reusing the string";

, StringBuilder, , , .

+1

"", ? , , . .

, , , , ACM-ICPC , , .

0

, , . , ( , "" ) , - , , . , , , .

, , :

dataTable.Columns.Add(new DataColumn() { ColumnName = "Subsite" });
dataTable.Columns.Add(new DataColumn() { ColumnName = "Library" });

, , - , . , IL-, .

0

Source: https://habr.com/ru/post/1713678/


All Articles