Archive for the ‘.NET’ Category

h1

Anonymous Types in C# 3.0

April 19, 2008

Anonymous 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”.

h1

Implicitly typed arrays in C# 3.0

April 17, 2008

After 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 -

image

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? :)

h1

.NET 3.5 Enhancements Training Kit

April 15, 2008

Another 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.

h1

Download Links

April 12, 2008

I 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

h1

Code Camp Oz

March 20, 2008

The 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?

h1

Object Initialization in C# 3.0

February 19, 2008

In 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.

h1

Property shortcuts in C# 3.0

February 9, 2008

I gave a talk about the new features in C# 3.0 at the Victoria .NET Dev SIG back in December. It was a packed house, with over 100 people and the turn out surprised me considering the fact that it was less than 10 days to Christmas.

Anyway, I had promised I would post my examples to the attendees and one of them asked about it recently. So, I decided to get my act together and blog about it.

Changes to C# 3.0 include features that range from what people refer to as syntactic sugar to some really cool stuff that you can do with LINQ. And covering them all in one post will get too big (for me). So, I’ll do one feature at a time, starting with Property Shortcuts.

Property shortcuts

Typically in C# 2.0, you would implement a property as shown below -

private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set { _firstName = value;}
}

It is a good thing to encapsulate your private data members, but more times than not, you will find yourself creating a wrapper for your private data members and nothing more. So, why not just expose these data members as public? Because, that would be bad practice - we would then lose the flexibility to change the implementation later.

C# 3.0 provides us with a compromise. You can now declare your property as shown below -

public string FirstName { get; set; }

By declaring it this way, there is no need to explicitly create a private data member to hold FirstName. So, you may ask - what is the difference between this and declaring the data member FirstName as public? The difference is that under the covers, C# creates a private data member for you. And if you decide to change the implementation later,  you can.

If you think that the declaration of FirstName is very similar to how you would declare it in an interface, you would be right. Declaration of FirstName in an interface will still look like this -

interface IName
{
    string FirstName { get; set; }
}

And if you wanted to declare this in an abstract class, then you can still do it -

abstract class AbstractName : IName
{
    public abstract string FirstName
        { get; set; }
}

Using the abstract keyword prevents the compiler from generating private data member for the property.

Is the old syntax supported? Absolutely. The only thing that will not work is a syntax that goes something like this -

// Will not work!
public string MyProperty { get; }

The reason for that is quite obvious, actually. If this syntax was indeed legal, how would you assign a value to the property? You can’t and because there is no explicit private data member, you cannot assign a value to that either. For the same reason, using a set; in isolation will also not work.

h1

Acropolis

August 9, 2007

I have to admit that one of the presentations I wish I hadn’t attended at Tech.Ed was the one on Acropolis. Maybe it wasn’t presented properly or maybe it is still early days for the product or maybe I just didn’t get it. The Apps created using Acropolis looks pretty cool but how you do it leaves a lot to be decided. Kathy Kam built a RSS reader using Acropolis and made changes to it to show how easily the UI could be changed, but I am not convinced yet…

h1

Software Factories

August 9, 2007

Tom spoke about the major Software factories that are in use now -

  • Web Client Software Factory
  • Web Services Software Factory
  • Smart client Software Factory
  • Mobile Client Software Factory

He gave a demo on the current Web Service Software Factory and also the yet to be released newer version of it. The new version is an interesting one, as you first define the model using DSL and then let the Software factory generate the code after that. I actually like this approach, but Darren got me thinking about the frequency at which the p&p team make breaking changes. All the guidance automation that people would have built/extended using the old Service Software factory would now be rendered redundant. Not a very good thought for people who would have done that.

Having said that I have to admit I am looking forward to playing around with the new “Modeling edition” Service Factory.

h1

EntLib 3.1

August 9, 2007

There are people who love EntLib and people who hate it. I would like to see myself somewhere in the middle. At Tech Ed today, Tom Hollander presented on EntLib 3.1 - he did not cover on the usual Application blocks that exist for Exception handling, logging, data access etc and instead concentrated on the two new ones - Validation Application Block and Policy Injection Application block.

The key areas that he covered in his presentation were -

  • How the Validation Application Block can be used to specify validation either using Attributes, programmatically or even in the configuration. He also spoke about how it is integrates nicely with ASP .NET, Win Forms and WCF
  • The Validation App Block contains rules to do the most common validations such as Null checking, Range checking, Validation using regular expressions, checking for characters and date lengths, property conversions, etc
  • How the Policy Injection Application block can be used for separating cross-cutting concerns from business logic