Four Rules for Implicit Types in SharePoint Development
One of the principal code modifications when using C# 3.0 is the introduction of implicit types. Having freshly concluded a sizeable code review for a manufacturing company where they had just completed framework retrofits, I found myself irritated with the prostitution of implicit types. So I thought that I would attempt to wrap some organization around appropriate use.
Implicit types are decorated through the use of the var keyword. The most notable instantiation is on construction of objects, but there are assortments of other tangible circumstances such as cast expressions (both orthodox in addition to safe casting) and orthodox/static method with explicit type arguments.
Implicit types are something to use with vigilance and care, they otherwise lessen inclusive code readability. And while mature and adhered to naming convention standards get over particular issues, there are four key rules to follow (IMHO) when considering implicit types:
1) When you are defining local variables inside methods wherever their type is easily grafted from the context (you can only use the var keyword for local variables anyways), use an implicit type. If you are declaring a SPList object with a descriptive variable name using a hydrated SPWeb, it is acceptable to use an implicit type. The type in that unambiguous circumstance should be unproblematic to grasp from the background.
2) When you are using an anonymous type, use an implicit type since giving it a type is not possible. This is a pretty straightforward case :)
3) If you are building largely named types, something like:
- var adambuenz = new <I, Like, Pie, It, Makes, Me, Happy,>()
increases readability to not use explicit type declaration. This is ordinary in SharePoint aggregation applications where numerous objects are rolled into complex collections. Often times instantiating the collection for use can lead to large declarations, of which var is a perfect use for stylistic truncation.
4) When using simple loops var can shorten code length and maintain readability. Like if you were doing a foreach (SPList list in SPWeb.Lists) you could implicit type the SPList variable with no loss.
Remember, since a lot of the use of implicit types is bound to the stylistic concerns of the code, established and adhered to coding naming conventions augment readability more than anything that the language will present.