Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Can the C# ‘var’ keyword be misused?

0.00/5 (No votes)
10 Jun 2011 1  
If the right-hand operand of an assignment is a new, there's no need to explicitly specify the type of the new variable being created unless the new variable will have to hold items of a more general type than the right-hand operand would indicate. I would consider the code clearer without the...
If the right-hand operand of an assignment is a "new", there's no need to explicitly specify the type of the new variable being created unless the new variable will have to hold items of a more general type than the right-hand operand would indicate. I would consider the code clearer without the duplication of the type name.

I would also consider "var" appropriate in cases where the right-hand operand is a factory method whose return type is clearly indicated by its name. For example, "var myCar = CarFactory.NewCar("whatever");". Note that the NewCar function might, given certain input, return a FordTaurus, but the declared return type of the function would be Car (from which FordTaurus would derive).

An important issue to consider, though, is whether some functions might have declared return types which could be, or might in future be changed to be, more specific than implied by their name. If one uses "var" to create a variable that is initially used to store the output of SomeFordFactory.NewCar, but it turns out that the NewCar function of SomeFordFactory is declared as returning FordCar, and the variable will later be used to hold some other type of vehicle, that could break things.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here