Click here to Skip to main content
15,886,017 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Can the C# ‘var’ keyword be misused?

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
10 Jun 2011CPOL1 min read 8.4K   1   2
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Unknown
Embedded systems programmer since 1994.

Comments and Discussions

 
GeneralReason for my vote of 5 This post hits on the most salient p... Pin
Jack Pines11-Jul-11 15:10
Jack Pines11-Jul-11 15:10 
GeneralExactly right. The problem is that C# is used for many diff... Pin
Chris Randle10-Jul-11 9:49
professionalChris Randle10-Jul-11 9:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.