

Anonymous Types in C# 3.0
April 19, 2008Anonymous Types allows developers to create a new type on the fly without an explicit declaration of the class. They can easily be explained with the help of an example -
var person0 = new
{
FirstName = "Mahesh",
LastName = "Krishnan",
Height = 182
};
var person1 = new
{
FirstName = "John",
LastName = "Doe",
Height = 165
};
var person2 = new
{
LastName = "Doe",
FirstName = "John",
Height = 175
};
Notice that the syntax makes use of both Implicitly typed variables as well as Object initialization methods that were explained in earlier posts. The new keyword usually is followed by the type that we wish to create, but while creating anonymous types, this is left blank and is followed immediately with a curly bracket as shown above. When the C# compiler sees a new anonymous class declared, it creates a new class under the covers. If we look at the types of these anonymous classes, they will look something like this -
<>f__AnonymousType0`3[System.String,System.String,System.Int32]
<>f__AnonymousType0`3[System.String,System.String,System.Int32]
<>f__AnonymousType1`3[System.String,System.String,System.Int32]
Notice that C# automatically generated the same Type for both person0 and person1, as they contained the same elements in the same order. person2 had a different order of the same elements and so, C# created a new type for it.
Usage rules/restrictions
- The properties in Anonymous types are all read only and therefore cannot be modified once they are created.
- Anonymous types cannot have methods.
- Anonymous types are always assigned to vars. This allows the compiler to assign the right type. But, if Anonymous types are used as return values or as parameters in a function, they will have to be passed in as Objects, as var is not a proper type
Projection
Anonymous types also supports Projection. So, if we have a declaration as shown below -
var LastName = "Nurk";
var FirstName = "Fred";
var person4 = new { LastName, FirstName};
then a new Anonymous type will be created with the read only properties LastName and FirstName. C# automatically projects the names of the variables to the names of properties in the anonymous class.
This also works while using objects, as shown below -
Person personObject = new Person
{
LastName = "Doe",
FirstName = "Jane",
Height = 156
};
var projectionFromClass = new
{
personObject.FirstName,
personObject.LastName
};
In this case, the object projectionFromClass will have an anonymous type that picks up the property names FirstName and LastName, which will hold the values “Jane” and “Doe”.

Implicitly typed arrays in C# 3.0
April 17, 2008After my C# 3.0 session at the Vic .NET Hands on day, there were several requests to post my examples in greater detail. So, I thought I’d continue the posts I started earlier on the same topic. The first 3 topic were -
Over a series of several posts, I plan to cover the remaining topics -
- Implicitly Typed Arrays
- Anonymous Types
- Auto Implemented Properties
- Extension Methods
- Lambda Expression
- LINQ
- Expression Trees
- Partial Methods
In this post, I plan to talk about Implicitly typed arrays. In C# 3.0, as with Implicitly typed local variables, you can also create an array of objects that use type inference to determine what array type they are. So the following statements would create an array of ints and doubles respectively, based on the types of the elements specified within the curly brackets -
//Examples of type inference
var myIntegers = new[] { 1, 2, 3, 4, 5 };
var myDoubles = new[] { 1, 2.1, 3.2, 4.3 };
Although the examples show primitive types as array elements, they are not limited to value types. The compiler will automatically infer the type based on the elements and assign it to the correct array type on the left hand side. The example below shows elements using a class Dog and its equivalent in C# 2.0
var myPets = new[]
{
new Dog( "Spike" ),
new Dog( "Snoopy" )
};
Dog[] pets = new Dog[2];
pets[0] = new Dog("Spike");
pets[0] = new Dog("Snoopy");
What you cannot do
For starters, you cannot mix and match types within your array. You also cannot have nulls when you have an array of value types. So, both the statements shown below are not legal -
//Cannot mix types
var mixedArray = new[] { 0, "one", 2, "three" };
//Cannot have nulls, when you mix with value types
var arrayWithNulls = new [] { 1, 2, null };
However, the following statement is acceptable, as it forces the compiler to create an array of nullable ints -
var arrayWithNulls = new[] { (int?)1, 2, 3, null };
Inference when using types from the same inheritance tree
When you have elements in the array that have types from the same inference tree, at least one of the types in the list have will have to be base class. For example, if we have the inheritance as shown below -
then, the first statement will not work, while the second one will -
var myPets = new[] { new Cat(), new Dog() } ;
var myPets1 = new[] { new Cat(), new Pet() } ;
If you want to create an array of IAnimal elements, then at least one of the elements in the array will have to be explicitly typed to an IAnimal as shown below -
IAnimal dog = new Dog();
var myPets2 = new[] { dog, new Cat() };
You cannot call it Implicitly typed, then. Can you?

.NET 3.5 Enhancements Training Kit
April 15, 2008Another link to go along with my earlier Download links post, is the one for the newly released .NET 3.5 Enhancement Training Kit - It can be downloaded from here.
It contains Hands on labs for all the new stuff such as ASP.NET MVC, ADO .NET Entity Framework and ADO.NET Data Services.

Download Links
April 12, 2008I promised the guys at the Victoria .NET Hands On day that I’ll post links to where Visual Studio 2008 Hands on labs can be found and where to get the VPC image with VS2008 et al installed. So, here they are:
Don’t forget that you need Virtual PC 2007 to use the VPC image

Presentation on Silverlight 2.0
April 9, 2008As part of RDN, I presented a ReadiDepth session on Silverlight 2.0 in Sydney yesterday. I will post the slide deck and samples on the Readify Web site soon, but if you missed the presentation and are in Melbourne tomorrow (Thursday 10th of October), please do drop by at Cliftons on Collins Street at 6:00pm.
For the early starters, there is also a morning session (7:00am) at Microsoft Theatre, Freshwater Place in Southbank.
If you are coming, don’t forget to register (AM Session, PM Session)

Code Camp Oz
March 20, 2008The official word is out. I will be presenting a session at Code Camp Oz this year. Check out the itinerary here.
Every one knows Ctrl+C is copy and Ctrl+V is paste. But, did you know that in Visual Studio, by hitting Ctrl+Shift+V, you could cycle through your previous copies? To find out little tips like these attend my topic - How well do you know your IDE?

Object Initialization in C# 3.0
February 19, 2008In older versions of C# when you create a new object and had to initialize some of its members, you had to write code similar to this -
Name name = new Name();
name.FirstName = “Fred”;
name.LastName = “Nurk”;
To make this sort of initialization easier, C# 3.0 introduces new syntax as shown below -
//Initialization with empty constructor
Name name = new Name
{ FirstName = “Fred”,
LastName = “Nurk”
};
The syntax also allows constructors with parameters -
//Intialization with constructor parameter
Name name = new Name(someParameter)
{
FirstName = “Fred”,
LastName = “Nurk”
};
You can also do nested initialization as shown below -
//Nested initialization
Customer customer = new Customer
{
CustomerName = new Name
{ FirstName = “Fred” },
Address = “400, Somwhere”
};
The syntax is pretty straight forward. You can initialize any public Property or member variable, by specifying the name of the Property/variable and initializing it with a = operator. More than one member can be initialized by using the comma operator. The only thing you cannot do is call a method or initialize a private member inside the initializer.

IE Style Tabs in Html
February 13, 2008Lot of web applications I’ve worked with have some kind of navigation that is implemented as Tabs. When I first started using tabs in Web Apps, I implemented them in tables, with the left hand side image of the tab in one cell, the middle part in another cell and the right hand side of the tab image in another cell.
That was before I discovered the beauty of CSS. The last few years I have been evangelising table-less design to every project/client that I go to and pretty much wherever I go, I take my “Tab” design with me. I cannot claim any originality to it, though. I first read about the Sliding door technique at “A LIST apart” a few years ago and I’ve been using it ever since.
Here is my implementation of it that resembles the IE 7.0 style tabs.
To do this, I created 6 images -
The html markup used to define the tabs is a very simple unordered list -
<div id="primaryNavigation">
<li><a href="#">Tab One</a></li>
<li id="current"><a href="#">Tab Two</a></li>
<li><a href="#">Tab Three</a></li>
<li><a href="#">Tab Four</a></li>
</div>
The markup is simple, because all the presentation information is present in the css file:
body
{
background:#fff;
margin:0;
padding:0;
color:#000;
font:10pt Tahoma, Helvetica, sans-serif;
}
#primaryNavigation {
float:left;
width:100%;
background: url( 'Images/tab-background.png' )
repeat-x 100% bottom;
}
#primaryNavigation ul {
margin: 0;
padding: 2px 10px 0px 3px;
list-style: none;
height: 36px;
}
#primaryNavigation li {
float: left;
background: url('Images/tab-left.png' )
no-repeat left top;
padding: 0px 0px 0px 3px;
height: 36px;
}
#primaryNavigation a {
float: left;
background: url('Images/tab-right.png' )
no-repeat right top;
padding: 6px 15px 0px 6px;
text-decoration: none;
color: black;
white-space: nowrap;
height: 36px;
}
#primaryNavigation a:hover {
color: black;
background: url('Images/hover-tab.png' )
no-repeat right top;
}
#primaryNavigation #current {
background:url('Images/current-tab-left.png' )
no-repeat left top;
float: left;
margin: 0;
padding: 0px 0px 0px 2px;
height: 36px;
}
#primaryNavigation #current a {
background-image: url('Images/current-tab-right.png' );
color: black;
white-space: nowrap;
height: 36px;
padding: 6px 15px 0px 6px;
}
Pretty simple, huh? This should work in most browsers, although I’ve tested in only on ID 7.0.

Type inference/Implicitly Typed local variables
February 11, 2008One of the new features in C# 3.0 is Implicitly Typed local variables. In scripting languages like JavaScript, you can define a variable like this -
var x = “some value”;
You can now do the same thing with C# 3.0 and although some people may consider this feature to be nothing more than syntactic sugar or a declaration shortcut for lazy programmers, it is needed for declaring anonymous types and while using LINQ (which I’ll cover in future posts).
C# uses type inference to automatically detect the type specified on the right hand side of the declaration. So, all these declarations are valid:
var myName = “Mahesh Krishnan”;
var myHeightInCms = 182;
var myWeightInKgs = 76.432;
var myPet = new Cat();
var dict = new Dictionary<int, string>();
var b = (ans == “Y“) ? true : false;
The main rule is that the variable has to be declared in one statement as shown above. Under the covers, C# substitutes var with a string or an int or whatever type is specified on the right hand side of the declaration. This is done at compile time and as a result type safety is not compromised. When you use Visual Studio 2008, you will also notice that intellisense works correctly for the type used.
You cannot have an empty or null declaration
The C# compiler needs to know the type of variable it is creating. So an empty variable declaration or a variable declaration that is assigned to null is not allowed.
//Neither statements are valid
//var uninitalized;
//var x = null;
Once a variable has been assigned, you cannot re-assign it to another type
In languages like JavaScript, you can assign an object to a variable and then re-assign another object of a different type to it. But in C#, this is not legal.
var myBooleanValue = true;
//Cannot change types!
//myBooleanValue = “false”;
You cannot mix and match types
//Not allowed
var x = (myBooleanValue) ? true : “false”;
As I mentioned earlier, type inference is done during compile time and a statement as shown above is not supported as the type of x can only be determined at run time. As a result, this statement is not valid.
You cannot create an array of vars
Creating an array of var as shown below is not allowed:
//Not valid
//var[] arr = new int[] { 10, 20, 30 };
You can still assign an array to an array variable declared as a var as shown below -
var arr = new int[] { 10, 20, 30 };
I will cover implicitly typed arrays in a later post.
Can only be used for local variables
One other major rule is that you cannot use var to declare member variables in a class. They are only allowed within a function body.
Use them wisely
Although, using var to declare a variable is a nice feature, use it wisely. Using it to declare known types such as integers and strings can make the code a bit unreadable. Another thing to avoid is using the keyword var as a variable. This is still allowed for backward compatibility, but you should avoid it at all costs.
(This is my second post on the new C# features. My first post on Property short cuts can be found here)