Search

Mar 27, 2009

Anonymous Types in C# 3.0

We all know about Abstract Type, generally we are creating Class which are Abstract Type, A Class has name assigned with it. Anonymous Type are Class without specifying the name to it. You can create Anonymous class by using new operator. Consider the following example.

class AnonymousType
{
public string Name { get; set; }
public int Age { get; set; }
public string Country { get; set; }
}
.
.
.
AnonymousType a1 = new AnonymousType { Name = "Marco" };
var a2 = new AnonymousType { Name = "Paolo" };
var a3 = new { Name = "Tom", Age = 31 };
var a4 = new { a2.Name, a2.Age };
var a5 = new { a1.Name, a1.Country };
var a6 = new { a1.Country, a1.Name };



The variables a1 and a2 are of the AnonymousType, but the type of variables a3, a4, a5, and a6 cannot be inferred type, see more on Local Type Inference. The var keyword get the type based on assigned expression which must with new keyword and without a type specified.



The variables a3 and a4 are of the same anonymous type because they have the same fields and properties. Even if a5 and a6 have the same properties (type and name), they are in a different order, and that is enough for the compiler to create two different anonymous types.



You can use anonymous type in array initializer too, lets see and example.




var ints = new[] { 1, 2, 3, 4 };
var arr1 = new[] {
new AnonymousType { Name = "Marco", Country = "Italy" },
new AnonymousType { Name = "Tom", Country = "USA" },
new AnonymousType { Name = "Paolo", Country = "Italy" }};
var arr2 = new[] {
new { Name = "Marco", Sports = new[] { "Tennis", "Spinning"} },
new { Name = "Tom", Sports = new[] { "Rugby", "Squash", "Baseball" } },
new { Name = "Paolo", Sports = new[] { "Skateboard", "Windsurf" } }};



While ints is an array of int and arr1 is an array of AnonymousType, arr2 is an array of anonymous types, each containing a string (Name) and an array of strings (Sports). You do not see a type in the arr2 definition because all types are inferred from the initialization expression. Once again, note that the arr2 assignment is a single expression, which could be embedded in another one.



You can read more features from my older post, Automatic Properties, and Object-Collection Initialization, Local Type Inference and Partial Methods.

Mar 25, 2009

Local Type Inference in C# 3.0


There are list of new features added in C# 3.0, I already cover Automatic Properties, and Object-Collection Initialization and Partial Methods in my older posts, here one more new feature which allow you to write more relaxed code. In another work you can define variable and use them without worrying about too much about their type, leaving it to the compiler to determine the correct type of a variable by inferring it from the expression assigned to the variable itself.

The price for using type inference might be less explicit code against the types you want to use, but in our opinion, this feature simplifies code maintenance of local variables where explicit type declaration is not particularly meaningful.

This might seem to be equivalent to defining a variable of type object, but it is not. The following code shows you that an object type requires the boxing of a value type (see b declaration), and in any case it requires a cast operation when you want to operate with the specific type (see d assignment):

var a = 2;       // a is declared as int
object b = 2; // Boxing an int into an object
int c = a; // No cast, no unboxing
int d = (int) b; // Cast is required, an unboxing is done

C# 3.0 offers type inference that allows you to define a variable by using the var keyword instead of a specific type. When var is used, the compiler infers the type from the expression used to initialize the variable.

The var keyword calls to mind the Component Object Model (COM) type VARIANT, which was used pervasively in Visual Basic 6.0, but in reality it is absolutely different because it is a type-safe declaration. The following code shows some examples of valid uses of var: x, y, and r are double types; d and w are decimal; s and p are string; and l is an int. Please note that the constant 2.3 defines the type inferred by three variables, and the default keyword is a typed null that infers the correct type to p.

public void ValidUse(decimal d)
{
var x = 2.3; // double
var y = x; // double
var r = x / y; // double
var s = "sample"; // string
var l = s.Length; // int
var w = d; // decimal
var p = default(string); // string
}

The next sample shows some cases in which the var keyword is not allowed:

class VarDemo
{
// invalid token 'var' in class, struct or interface member declaration
var k = 0;
// type expected in parameter list
public void InvalidUseParameter(var x) { }
// type expected in result type declaration
public var InvalidUseResult()
{
return 2;
}
public void InvalidUseLocal()
{
var x; // Syntax error, '=' expected
var y = null; // Cannot infer local variable type from 'null'
}
// …
}

The k type can be inferred by the constant initializer, but var is not allowed on type members. The result type of InvalidUseResult could be inferred by the internal return statement, but even this syntax is not allowed .

Partial Methods in C# 3.0

In C# 2.0 Partial Class has been added, which was I personally believe very good features to work in multi-developer environment.

One more new feature added in C# 3.0; Partial Method. I already talked about Automatic Properties, and Object-Collection Initialization which also introduced in C# 3.0. Partial Method is a method which must reside [only signature] into Partial Type [Partial Class] and if define somewhere then will get executed. This basically a rule created by one, if other want to implement then go ahead or leave it blank. I can compare it with Interface method; although its major difference between Interface method and Partial method. In Interface method if you does not implement then the type which implement that interface MUST be abstract; but in the case of Partial Method, its not abstract but its Partial.

There are few rules if you want to work with Partial Methods:

  • A method must be declared within Partial Class or Partial Structure
  • A method cannot have access modifiers. [virtual, abstract, new, sealed...]. They are always private
  • A method must return void
  • A method cannot have out parameter
  • A method definition hast to end with ';'
Here is the simple example of Partial Methods

partial class PartialMethods
{
partial void DoSomeWork();
}

If you build with this code, it will work fine although we haven't write body of this function. If you see the Manifest you wont find this method anywhere. The only constructor will part of PartialMethods class.

PartialMethod1

Now let me write body for the method and check manifest again

partial class PartialMethods
{
partial void DoSomeWork();
}

public partial class PartialMethods
{
partial void DoSomeWork()
{
//Do your work here
}
}


PartialMethod2

Now we can see the method, this class is not full class but as partial methods are private, you cant not access from outside, you have to call within that class. Partial method allow developer to create rule which can be implemented later but only once.

Mar 14, 2009

Object and Collection Initialization in C# 3.0

My last post I speak about Automatic Properties, and how we can use them. Here we will discuss the Object and Collection Initialization in C# 3.0. In general we are do initialize our property either inside constructor [standard method] or by calling some methods or assigning value directly to public property. Let's see how.

public class Test
{

public class InitializeTest
{
public int Id { get; private set; }
public string Name { get; private set; }

public InitializeTest()
{

}

//Initialize using constructor
public InitializeTest(int intId, string strName)
{
Id = intId;
Name = strName;
}

//Initialize using method
public void SetId(int intId)
{
Id = intId;
}
}

static void Start()
{
//Initialize using constructor
InitializeTest objInitializeTest1 = new InitializeTest(1, "a");

//Initialize using method
InitializeTest objInitializeTest2 = new InitializeTest();
objInitializeTest2.SetId(1);
}
}

Lets talk about initialize using constructor, we have two constructor, one is default and another is accepting two arguments. so far so good. Lets say I have added new property into my class, then? have to create new overloaded constructor? or modify two argument constructor with three which will raise few more errors!!! First one will be better option.

public char Sex { get; set; }

//Initialize using constructor
public InitializeTest(int intId, string strName) : this(intId, strName, 'M') { }

//Initialize using constructor
public InitializeTest(int intId, string strName, char cSex)
{
Id = intId;
Name = strName;
Sex = cSex;
}

Now to avoid this lets see what is in Object Initialization provided by C# 3.0. We can simply use single argument constructor to initialize the member of class, lets add one more property to class name Birthdate.

public class InitializeTest
{
public int Id { get; set; }
public string Name { get; set; }
public char Sex { get; set; }
public DateTime Birthdate { get; set; }
.
.
.
.
}

You may notice here that I have removed private scope why? I will explain it later.

static void Start()
{
InitializeTest objInitializeTest3 = new InitializeTest() { Id = 1, Birthdate = DateTime.Now, Name = "Name", Sex = 'M' };
}

That's it!!! initialize the value of property right after constructor inside the curly braces. You can also assign few or complete list. Now if we make Id property private we can't use here [outside of the class] that is the reason for removing private to get accessor. How it works?

The syntaxes used to initialize an object (standard and object initializers) are equivalent after code is compiled. Object initializer syntax produces a call to a constructor for the specified type (either a reference or value type): this is the default constructor whenever you do not place a parenthesis between the type name and the open bracket. If that constructor makes assignments to the member fields successively initialized, the compiler still performs that work, although the assignment might not be used. An object initializer does not have an additional cost if the called constructor of the initialized type is empty

This can be done on parameterize constructor as well.

We seen object initialization, same was we can achieve collection initialization. Let's see how. First lets add one generic collection to out class and then will do initialization.

public class InitializeTest
{
.
.
public List<string> FamilyMembers { get; set; }
.
.
}
.
.
static void Start()
{
InitializeTest objInitializeTest4 =
new InitializeTest() { FamilyMembers = { "First", "Second", "Third" } };
}
.
.

Its really easy and we have eliminated quite a bit of typing.

Mar 13, 2009

Automatic Properties in C# 3.0

Automatic properties are introduced in 3.0 of C#. Using automatic properties you can save your lots of time and typing.

Up to now we were writing following code to create single property.

public class PropertyTest
{
private string _strTest;

public string strTest
{
get { return _strTest; }
set { _strTest = value; }
}
}

Now look at the automatic properties bellow.

public class PropertyTest
{
public string strTest { get; set; }
}

Only single line of code!!!
We can even restrict the get and set property, like we need set property to be private and get property to be public; yes we can do that too.

public class PropertyTest
{
public string strTest { get; private set; }
}


Although its time saver there is few limitation for this, lets list out those limitations.
  1. Automatically implemented properties must define both get and set accessors, if not have to make them abstract.

    //Gives you error
    public class PropertyTest
    {
    public string strTest { get; }
    }

    //Works fine
    abstract public class PropertyTest
    {
    abstract public string strTest { get; }
    }

  2. You can't initialize them in declaration, although you can do it into Constructor

    public class PropertyTest
    {
    public string strTest { get; set; }

    public PropertyTest()
    {
    strTest = "Test String";
    }
    }


Mar 11, 2009

Free ASP.NET MVC Tutorial

The announcement made by Scoot Guthrie on 11-March-2009 that you can now download the tutorial for MVC.

The free ASP.NET MVC Tutorial having following points covered along with images.

  • File->New Project
  • Creating the Database
  • Building the Model
  • Controllers and Views
  • Create, Update, Delete Form Scenarios ViewData and ViewModel
  • Partials and Master Pages
  • Paging Support
  • Authentication and Authorization
  • AJAX Enabling RSVPs Accepts
  • Integrating an AJAX Map
  • Unit Testing

You can find the original post by ScootGu from here, and the PDF from here.

A sample application for ASP.NET MVC you can find it from Codeplex.