Use of var in CSLA Code

Use of var in CSLA Code

Old forum URL: forums.lhotka.net/forums/t/7140.aspx


Vinodonly posted on Sunday, June 21, 2009

Hi Rocky,

While going through the C# 2008 book and examing the code, there was lot of places where var was used instead of the actual data type..

If we are reading the code blocks from book then it is very confusing as difficult to determind what will be the actual data type and specially when we are trying to understand how some features were implemented.

Is there any possibility in future to use actual types in code instead of var..

tiago replied on Sunday, June 21, 2009

Good point!

RockfordLhotka replied on Monday, June 22, 2009

I suspect you'll need to learn to like the 'var' keyword. I'm not alone in thinking it is one of the best improvements to the language in recent memory, and I can't imagine coding without it.

In my view, the compiler is finally smart enough to do something this trivial, thereby saving me a lot of typing and effort, and making my code more agile and maintainable.

JoeFallon1 replied on Tuesday, June 23, 2009

When I had to translate the C# code to VB I did not have too much trouble with var. In fact many of the technical reviewers suggested using type inference in more places in the VB code - especially when it was crystal clear what the type would be simply by looking at the right hand side of the statement. In a couple of places they thought the type was unclear and the readability of the code could be improved by declaring it fully. But that was a very small subset.

Joe

RockfordLhotka replied on Tuesday, June 23, 2009

I try not to use var/Dim (type inference) when the type is clearly
ambiguous:

var x = 1;

what is that? An int? A double? A long? A short? Who knows...

var x = "Hi there";

that's very clear - it is a string, and it saved me some typing.

var x = new InvoicePoster();

I think that is very clear, and in fact brings C# into line with VB in terms
of typing less

Dim x As New InvoicePoster

This syntax has been around for over 10 years, and I think is entirely
clear.

var x = CustomerEdit.GetCustomer(123);

I think that's very clear too, and now it saved me a lot of typing. Is it a
CustomerEdit or an ICustomerEdit? I don't know, but honestly I don't care
either, and that's why this is (imo) good coding. I could change the factory
to switch between those types, and assuming I'm reasonably competent in
terms of my OO design, it will not only work fine, but my life was
substantially easier by using var.

Rocky

Copyright (c) Marimer LLC