65.9K
CodeProject is changing. Read more.
Home

Can the C# ‘var’ keyword be misused?

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Jun 10, 2011

CPOL

1 min read

viewsIcon

8772

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.