Welcome to WindowsClient.net | Sign in | Join
Wednesday, October 22, 2008 10:19 PM rendle

Type inference and refactoring

There's been a lot of discussion around type inference and the var keyword in C# 3.0 since it was released. Personally I'm a fan, as I never enjoyed having to type things like
 
using (SqlDataReader reader = cmd.ExecuteReader())
 
(Intellisense is great, but there are so many types that start with "SqlData" that it was still annoying.)
 
Anyway, I'm working on a business object framework at the moment, have been for a long time, and as I go along I refactor a lot for best practices. I've just been through and looked at all the methods that return arrays to check whether that's actually the most appropriate type; usually, it isn't. I found a lot of places where the only functionality possibly required by the consumers was iteration or LINQ-related, meaning the correct return type was IEnumerable<T>. Since, for example, "string[]" implements IEnumerable<string>, I could very quickly change the return type of the method and worry about the implementation, if necessary, later.
 
In about half the instances where I made this change, the references to the method elsewhere in the code were pre-C# 3.0, so they explicitly used the array type as the variable declaration and I had to go through and change them. Naturally, I changed them to var, which was a hell of a lot easier than specifying the actual IEnumerable<T> in every case.
 
In the other half of the references to these methods, the ones written post-C# 3.0, I'd used var already. And in all except one case, after I'd changed the return type of the method, the calling code required no modification at all. That one case involved a "x.Length > 0" check and an "IndexOf(x,y) > -1", which were pointed up via compilation errors and swiftly changed to "x.Any()" and "x.Contains(y)".
 
So, to the extent that consumers are less interested in the specific type being returned than in the properties and methods it exposes, using type inference can make refactoring considerably easier. That's a good argument for me.
Filed under: ,

Comments

# re: Type inference and refactoring

Tuesday, December 30, 2008 6:42 PM by Dave

I agree completely. var is great, makes for better refactoring, and makes the code cleaner. Really with VS2008, C#, Resharper, you get a very productive environment. I would say more so than even the scripting languages (Groovy, Ruby, Python) because you get the static guarantees. Great blog by the way.

Leave a Comment

(required) 
(required) 
(optional)
(required) 
 
Page view counter