I often see in C# code the following convention:
some_type val;
val = something;
like
DataTable dt;
dt = some_function_returning_datatable();
or
DataTable dt = new DataTable();
dt = some_function_returning_datatable();
instead of
some_type val = something;
DataTable dt = some_function_returning_datatable();
I initially assumed that this was a habit left over from the days when you had to declare all local variables at the top of the scope. But I’ve learned not to dismiss so quickly the habits of veteran developers.
(In my 3rd code section will it not be wastage of memory when we assign dt first with new and then from function)
So, is there a good reason for declaring in one line, and assigning afterwards?
Yes, it will indeed. Only relatively minor – creating a useless
DataTableobject – but still wasteful and unclear.Only if you don’t have the value immediately. For example:
Often this can be improved either using a conditional operator or extracting that code into a method. Sometimes it doesn’t work out that way though.
For simple situations of:
Or
You should absolutely refactor to
One other interesting situation where the declaration point does make a difference is in captured variables, although normally not the way it’s intended:
vs
In the first snippet, each delegate will capture the same variable, so they would all effectively see the last value returned from
SomeFunction. In the second snippet, each delegate will capture a separate “instance” ofx.