Search This Blog

2009-06-03

C# 3.0 Tutorial -6:Type Equivalence

Type Equivalence

Type equivalence involves determining if two values are of the same type. In this case, we are concerned with type equivalence of objects instantiated from anonymous classes.

This comes up in practice when assignment is considered. Let's take an example.
var x = new {
Real = 5.4,
Complex = 2.8
};
var y = new {
Real = 1.9,
Complex = 5.3
};
x = y;Remember from the first part of the series that C# 3.0 is statically typed. That means that the variables x and y both have and retain a given type. Therefore, if the assignment is to work then y has to be of the same type as x (we don't have to consider subtyping here, since anonymous classes always inherit from object).

Two anonymous types will be considered equivalent if all of the following properties are true:
They have the same number of fields
They have fields of the same name declared in the same order
The types of each of the fields are identical
In the previous example, this is the case. However, any of the following changes to the anonymous type that was instantiated to give y will result in the types not being equivalent and the assignment resulting in a compile time error.
// Not equivalent due to an extra field.
var y = new {
Real = 1.9,
Complex = 5.3,
Conjugated = -5.3
};
// Not equivalent - fields in a different order.
var y = new {
Complex = 5.3,
Real = 1.9
};
// Not equivalent; different types (int != double)
var y = new {
Complex = 4,
Real = 2
};

Code Snippet(Aspx page)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CSharp3_TypeEquivalance : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Type Equivalance
var x = new { Real = 4.5, Complex = 2.8 };
//Not equivalent due to an extra field
var y1 = new { Real = 4.6, complex = 2.9, id = "123" };
//Not equivalent - fields in a different order
var y2 = new { Complex = 5.3,Real = 1.9};
// Not equivalent; different types (int != double)
var y3 = new{Complex = 4,Real = 2};


//have the same number of fields ,have fields of the same name declared in the same order ,The types of each of the fields are identical

var y4 = new { Real = 1.9, Complex = 5.3 };


Response.Write("x.GetType() == y1.GetType() :" + ((x.GetType() == y1.GetType()) ? "Yes" : "No,Not equivalent due to an extra field"));
Response.Write("<br/>");
Response.Write("x.GetType() == y2.GetType() :" + ((x.GetType() == y2.GetType()) ? "Yes" : "No,Not equivalent - fields in a different order"));
Response.Write("<br/>");
Response.Write("x.GetType() == y3.GetType() :" + ((x.GetType() == y3.GetType()) ? "Yes" : "No,Not equivalent; different types (int != double)"));
Response.Write("<br/>");
Response.Write("x.GetType() == y4.GetType() :" + ((x.GetType() == y4.GetType()) ? "Yes,have the same number of fields ,have fields of the same name declared in the same order ,The types of each of the fields are identical " : "No"));
Response.Write("<br/>");



if (x.GetType() == y1.GetType())
{
Response.Write("<br/>");
Response.Write(x.Real);
}
}
}

Output :

x.GetType() == y1.GetType() :No,Not equivalent due to an extra field
x.GetType() == y2.GetType() :No,Not equivalent - fields in a different order
x.GetType() == y3.GetType() :No,Not equivalent; different types (int != double)
x.GetType() == y4.GetType() :Yes,have the same number of fields ,have fields of the same name declared in the same order ,The types of each of the fields are identical

tags:what is Type Equivalence in 3.0/3.5,how can I implement Type Equivalence in c# 3.0/3.5

C# 3.0 Tutorial -5:Anonymous Types

Anonymous Types

Anonymous simply means "without a name", and you can safely read the word "type" as "class" in this case. That is, in this section we are going to discuss the idea of classes without names.

In C# 2.0 we saw the introduction of anonymous methods. One of the consequences of a method having no name is that we had to take a reference to it - stored in a delegate type - right away, so we had some way to refer to it. The analogy with anonymous classes is that we are required to instantiate them right away. Therefore, the construct for creating an anonymous class also instantiates that class.

In C# 3.0, anonymous classes are greatly limited compared to standard classes. They can only inherit from object and their only memebers are private fields each with a matching read/write property.

With all of these things in mind, let's see how we declare and instantiate an anonymous type.
var MyProduct = new {
Name = "Vacuum Cleaner",
Price = 94.99,
Description = "Really sucks! Have your carpets clean in no time."
};
There are a couple of things to notice here. First is that we do not have a name for the class. Therefore, there is no type that we can write before the name of the variable when declaring it. What we can do, however, is to write "var", which leaves the compiler to work out the type for us. While the types are anonymous as far as we should care, the compiler and runtime actually do have some way of identifying them.

The second thing to notice is that we have used the "new" keyword but without specifying a type name. Instead, we have placed something after it that looks just like the object initializers we were looking at a few moments ago. This is not a co-incidence: we actually are initializing the object created by new. The question is, where is the definition of the class?

The class is created by looking at the initializer. For each name assigned to inside the initializer (Name, Price and Description in this case), a private field is created along with a get/set property. In this case, the class might look like this:
class __NO_NAME__ {
private string _Name;
private double _Price;
private string _Description;

public string Name {
get { return _Name; }
set { _Name = value; }
}
public double Price {
get { return _Price; }
set { _Price = value; }
}
public string Description {
get { return _Description; }
set { _Description = value; }
}
}
Note that the types of the fields are worked out by looking at what is being assigned to the property. Therefore, you are not allowed to assign a null value. It is the same type inference process that we have seen time and time again in C# 3.0.

Since anonymous classes are just classes and instances of them are just objects, you can do all of the things you'd expect to be able to with them, from simple things like accessing their properties through to more complicated things such as reflection.

Code Snippet(Aspx page)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CSharp3_AnonymousType : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

//Anonymous Types
//Its look likes a class which have three following property
//it is read only property ,we can not change the value further
var MyProduct = new { CustName = "Manab", CustID = 100450, Location = "Kolkata" };
Response.Write("<br/>");
Response.Write("Cust Name : " + MyProduct.CustName + " Cust ID:" + MyProduct.CustID);

}
}

Output:
Cust Name : Manab Cust ID:100450

tags:what is Anonymous Types in c# 3.0/3.5,new features in c# 3.0/3.5,how can we implement anonymous types in c# 3.0/3.5

2009-06-02

C# 3.0 Tutorial -4:Object Initializers

It is fairly common in C# code to see an object be instantiated using the "new" keyword and then having its fields and/or properties set. Until C# 3.0, this could only be done by instantiating the object, storing it in a variable and then doing assignments to the various properties. In C# 3.0, object initializers make this possible within a single expression.
Suppose we want to instantiate a 5 year old male monkey called Norbert and add it to the jungle. In previous versions of C# we would have written:

Monkey NewCreation = new Monkey();
NewCreation.Name = "Norbert";
NewCreation.Sex = SexEnum.Male;
NewCreation.Age = 5;
Jungle.Add(NewCreation);

A few things are frustrating here. First is that if we have to mention the variable, NewCreation, each time. Second, we may not really need the variable NewCreation at all - we just want to add a monkey to the collection. Finally, it would be better from a linguistic point of view if we could have pulled the Add ahead of the monkey creation, so when you read the code you can see the purpose of creating the new monkey.

Object initializers allow us to set the initial values of fields or properties of an object as part of the new statement. For example, we can re-write the above like this:
Monkey NewCreation = new Monkey() {
Name = "Norbert",
Sex = SexEnum.Male,
Age = 5
};
Jungle.Add(NewCreation);

Here we have added a set of curly braces at the end of the "new" expression. Inside them, we can do assignments to the fields and properties without having to write the name of the object that is being referred to. Note the use of commas between the assignments rather than semicolons.

The fact that we don't have to name the object we are initializing - that is, setting the fields/properties of - means we can do a further refactoring:
Jungle.Add(new Monkey() {
Name = "Norbert",
Sex = SexEnum.Male,
Age = 5
});Now the intermediate variable is gone. Finally, if there are no parameters to pass to the constructor, we are permitted to save ourselves two more characters and remove the brackets after the type name:
Jungle.Add(new Monkey {
Name = "Norbert",
Sex = SexEnum.Male,
Age = 5
});

Initializing Nested Objects
Our Monkey class may have, as one of its fields, an field that holds an instance of the Tail class. In this case, there are two possibilities. One is that the class does not instantiate the Tail for us. In this case, we can use the new keyword to instantiate it and set properties of it - basically, just nesting what we already know.
Jungle.Add(new Monkey {
Name = "Norbert",
Sex = SexEnum.Male,
Age = 5,
Tail = new Tail { Length = 50 }
});
The other possibility is that the class does instantiate tail and we just need to set some properties of it. In this case we can omit not only the "new" keyword, but also the name of the class too, since that can be worked out by the compiler.

Jungle.Add(new Monkey {
Name = "Norbert",
Sex = SexEnum.Male,
Age = 5,
Tail = { Length = 50 }
});

You can nest as deeply as you wish, but be careful not to harm readability. Good use of whitespace can help on that front.
Collection Initializers
Collections can contain many values. Sometimes you will create a collection and then immediately add some values to it. Just as object initializer syntax made a common use case neater for objects, collection initializer syntax makes one neater for collections.

Again, let's take an example. Notice that I am already using the new C# 3 "var" keyword.
var Jungle = new List();
Jungle.Add(new Monkey());
Jungle.Add(new Tiger());
Jungle.Add(new Panda());Using a collection initializer, we can write this as:
var Jungle = new List
{ new Monkey(), new Tiger(), new Panda() };

There are some rules concerning the use of collection initializers. First, if you are writing your own collections and want them to work with collection initializer syntax, they must implement the ICollection interface. Second, the elements of the collection must all be of the same type (or more precisely, they must all have an implicit coercion to a single type).

Initializer Performance
Shorter code doesn't always mean a performance improvement at runtime. In this case, the new object initializer syntax will almost certainly compile down to the same IL instructions as if you had not used it. You might save a tiny amount of memory due to not having to allocate space for the local variable. However, the compiler should have been able to optimize that away anyway. In short, expect equivalent performance: no better and no worse.


Code Snippet:(ASPX Page)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CSharp3_ObjectInitializer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomerHandler ch = new CustomerHandler();

//Previously we have to do as follows

CustomerDet cd = new CustomerDet();
cd.Name = "Manab";
cd.Location = "Kolkata";

Response.Write(ch.DisplayCustomer(cd)+"<br/>");
//No using bject initializer we can do it as follows
Response.Write(ch.DisplayCustomer(new CustomerDet {Name="Ranjan",Location="Mumbai" })+"<br/>");

//but can't acess method as follows
//Response.Write(new CustomerHandler{DisplayCustomer(new CustomerDet { Name = "Ranjan", Location = "Mumbai" })});

}
}
public class CustomerHandler
{
public string DisplayCustomer(CustomerDet custData)
{
return custData.Name + " " + custData.Location;
}
}

public class CustomerDet
{
private string _Name;
private string _Location;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string Location
{
get { return _Location; }
set { _Location = value; }
}

}

Output:
Manab Kolkata
Ranjan Mumbai


tags:what is object initializers in c# 3.0 or 3.5

2009-06-01

C# 3.0 Tutorial -3:Lambda Expressions

Lambda Expressions

The term "lambda expression" sounds somewhat frightening at first, but there’s no reason to be sheepish. In fact, the lambda calculus – a very simple language where everything is expressed in terms of functions – dates back to the day before we had computers, making it some of the earliest theoretical Computer Science work.A lambda expression simply defines an anonymous function. A function is something that takes one or more parameters (just as a method does) and uses them in computing some value. That value becomes the return value for the function. In C# 3, the "=>" syntax is used to write a lambda expression. You place the parameters to the left of the arrow and the expression to compute to the right.For example, here is a function that adds one to the value it is provided with:

x => x + 1

How does this work? Well, it takes one parameter x and then returns the result of doing "x + 1". You can write a Lambda expression that multiplies to numbers quite easily too:

(x, y) => x * y

Here we have taken two parameters, x and y, and the result is the multiplication of them. Note that if we have more than one parameter, we have to place them in parentheses. How about if you do not wish to take any parameters? In this case, you put an empty set of parentheses in place of the parameter.

() => new Beer()

The above function takes nothing and returns beer; this is rarely implemented in the real world. If you want to do something more complex, you can supply a block to the right of the arrow. In this case, you should write a return statement, unless you do not wish to return a value (which is allowable, though not the common case).

(x, y) => {
var result = x + y;
return result;
}

Using Lambda Expressions

At this point you could be forgiven for thinking, "well that's neat, but why?" C# 2.0 added support for anonymous methods. However, the syntax was rather verbose for a feature that, at least amongst some programmers, is used quite often. Let's look at a couple of examples where anonymous methods were used before and see the improvement that we get by using lambda expressions instead.In this first example, we will take a list of strings, sort them by length and then display the output. We use an anonymous method to give the comparisons.

// Some words.
var Words = new List { "amazingly", "my", "badger", "exploded" };
// Sort them by word length.
Words.Sort(delegate(string a, string b)
{
return a.Length.CompareTo(b.Length);
});
// Show results.
foreach (string Word in Words)
Console.Write(Word + " ");

This prints "my badger exploded amazingly" on the console. We can re-write the sort using a lambda expression.

// Sort them by word length.
Words.Sort((a, b) => a.Length.CompareTo(b.Length));

Which is a lot neater. For a second example, suppose we are rendering some forum markup tags to HTML. We are going to match a tag with a regex, check if the tag is in a list of allowed tags and, if it is, render it to HTML. Otherwise, we'll just leave it unrendered. Here is the original implementation.

// List of tags we accept.
var AcceptedTags = new List<string> { "b", "u", "br" };
// Text to render.
var ToRender = "[b]Bold, [i]bold italic[/i], just bold again.[/b][br]";
// Regex to match tags.
var FindTags = new Regex(@"\[(/?)(\w+)\]");
// Render it.
string Output = FindTags.Replace(ToRender,
delegate (Match m) {
return AcceptedTags.Contains(m.Groups[2].Value) ?
"<" + m.Groups[1].Value + m.Groups[2].Value + ">" :
m.Value;
});

Here we are using an anonymous method to specify code to generate the replacement string. We can replace that with a lambda expression too.

string Output = FindTags.Replace(ToRender,
m => AcceptedTags.Contains(m.Groups[2].Value) ?
"<" + m.Groups[1].Value + m.Groups[2].Value + ">" :
m.Value);

Lambda Expressions And Type Inference

One difference you may have spotted between lambda expressions and the original anonymous method syntax is the absence of types on the parameters. You actually can write the types in if you wish:

(int x, int y) => x + y

Be aware that you need the parentheses for a single parameter if you're going to write a type annotation:

(int x) => x + 1

Even here, there is something more special going on, since nowhere have we declared the type of value that will be returned by the lambda expression. With anonymous methods we had to do that.

In the previous article, I talked about type inference. As a very quick recap, this involves working out the types of variables based on information available in the code rather than making the programmer write them in. This is exactly what is happening here. The interesting question, then, is where is the type information coming from this time?

When a method expects to be passed an anonymous method as a parameter, it uses a delegate type. This delegate type contains the types of the parameters. When a lambda expression is used, it is often being passed as a parameter. Therefore, the delegate type of the parameter will, in turn, enable to compiler to work out what the types of the lambda expression's parameters are.

If you're wide awake, you might be wondering what happens when you have a generic delegate type as a parameter of a method and pass a lambda expression there. And the answer is that yes, you can do this, generic types will be inferred and it should all work out just fine. In fact, some of what LINQ does depends on it working.

Conclusion

In this article we've seen extension methods and lambda expressions. I've taken the time to dive into some of the ugly details, but don't worry if some of them haven't sunk in just yet.

Extension methods offer some powerful new possibilities, but we need to take care in how we use them from a software engineering angle. Don't expect to be using them every day, but remember them for those times when they really are the right thing to use.

Lambda expressions, on the other hand, are for regular use. Even if you aren't doing much higher order programming today, if you plan on using LINQ you soon will be. The biggest hurdle most people have to get over is realizing that it is possible (conceptually, at least) to treat code the same as data. Once you get comfortable with that idea, using anonymous methods or lambda expressions doesn't feel so unusual. Practice and experience help. I'd recommend trying to learn a functional programming language, but if you're reading this you're probably wanting to get C# 3.0 cracked first.

In the next article in the series we'll look at object initializers and anonymous types. These make it easier to build up data structures and set initial values for fields in objects and structures. With that, we will have seen all of the language features that act as the building blocks for LINQ, which will be covered in the final part in the series.

Code Snippet(Asp .NET)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CSharp3_LambdaExpression : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Flowing example is of Lambda Expressions where Words.Sort((a, b) taking two input param and return a output
//as a.Length.CompareTo(b.Length));
//as the list array is consisit of three param the right hand side will executed 6 times total(2 for each)
var Words = new List { "AB", "A", "ABC","ABCD" };
Words.Sort((a, b) => a.Length.CompareTo(b.Length));
Response.Write("
");
Response.Write(Words[0] + " " + Words[1] + " " + Words[2] + " " + Words[3]);


//string x = "2";
//string y = "4";
//((x, y) => x + y);
}
}

Output:

A AB ABC ABCD

tags:what is lambda expression in 3.0/3.5,how can I implemet lambda expression in c# 3.0/3.5