Thursday, December 22, 2011

Best Practices: Initialization Myth #1

[Note] I have used DataTable only for explaining. It can be any data type.

Usually we do the mistake of initializing unnecessarily like this.

[VB]

Dim dt as New DataTable

dt= CreateDataTable()

[CS]

DataTable dt= new DataTable();

dt=CreateTable();

We don’t have to initialize the dt variable here and it is unnecessary. Because we are overwriting it.

We can just declare the variable and then assign the value from the function or any other expressions.

[VB]

Dim dt as DataTable

dt= CreateDataTable()

[CS]

DataTable dt;

dt=CreateTable();

Or Simply

[VB]

Dim dt as DataTable = CreateDataTable()

[CS]

DataTable dt = CreateTable();

No comments:

Post a Comment