65.9K
CodeProject is changing. Read more.
Home

Can the C# ‘var’ Keyword be Misused?

starIconstarIconstarIconstarIconstarIcon

5.00/5 (14 votes)

Nov 20, 2009

CPOL
viewsIcon

10082

Can the C# ‘var’ keyword be misused?

It can be misused of course, if you can't figure out by glancing at the code, what the code does. In your example, for one, it is bad, but then again, GetData() is bad too, what does the function do? If the function had a meaningful name, then maybe the var declaration would actually be good in clearing confusion:

var productsTable = GetProducsDataTable();

In my opinion, the var here is excellent, it doesn't confuse the reader with unnecessary details like what the datatype is exactly (a dictionary, a datatable, etc.) but it does tell him what it semantically contains, which is probably what he needs to know. If he does need to know the type, he can use the various ways mentioned here, like mousing over the method, or jumping to its declaration, or mousing over the productsTable variable.