Why declare a variable in one line and assign it in the next?

I often see the following convention in C # code:

some_type val;
val = something;

as

DataTable dt;
dt = some_function_returning_datatable();

or

DataTable dt = new DataTable();
dt = some_function_returning_datatable();

instead

some_type val = something;
DataTable dt = some_function_returning_datatable();

It was originally supposed to be a habit left after you had to declare all the local variables at the top of the area. But I learned how to quickly give up the habits of veteran developers.

(In my third section of code, this will not be memory loss when assigned dtfirst with new, and then from a function)

So, is there a good reason for a single line declaration and subsequent assignment?

+3
source share
5 answers

In my third section of code, this will not be memory loss when we first assign dt to new and then from function

, . - DataTable, .

, ?

. :

string x;
if (someCondition) {
    // Do some work
    x = someResult;
} else {
    // Do some other work
    x = someOtherResult;
}

, . .

:

Foo x = SomeInitializationWithNoUsefulSideEffects();
x = SomeUsefulValue();

Foo x;
x = SomeUsefulValue();

Foo x = SomeUsefulValue();

, , , , :

int x;
for (int i = 0; i < 10; i++) {
    x = SomeFunction();
    actions.Add(() => Console.WriteLine(x));
}

for (int i = 0; i < 10; i++) {
    int x = SomeFunction();
    actions.Add(() => Console.WriteLine(x));
}

, , SomeFunction. "" x.

+17

-.

, . #:

some_type val;
val = something;

:

some_type val = something;

DataTable dt = new DataTable();
dt = some_function_returning_datatable();

:

DataTable dt = some_function_returning_datatable();

, , # .

+9

. . CLR , , .

int i=5;

.

, int = 5; CLR integer.

0
SomeType someVar;
someVar = new(SomeType);

SomeType someVar = new(SomeType);

. , , , , , .

SomeType someVar = new(SomeType);
someVar = GetSomeTypeFromSomewhereElse();

, , -, . , . , .: D

, , someVar , .

0

, , - . , , , , , , :

, - " "; , , :

  • , , , (, )
  • Variable names and an initialization expression assume that the loop is initialized (for example, "var currentFoo = firstFoo;")

The longer the scope of the variable, the more likely it is that I will use separate initialization and declaration if the value ever changes.

0
source

All Articles