Search This Blog

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

2009-05-31

C# 3.0 Tutorial -2:Extension Methods

In the beginning – that is, in C# 1.0 – the methods belonging to a class were defined within the body of the class. C# 2.0 changed that somewhat. By introducing partial classes, the methods making up a class could be defined in more than one place. However, they were all collected together at compile time, so it was nothing particularly new. Anonymous methods were something new, however. Conceptually, anonymous methods are associated with no class at all. C# 3.0 continues the journey with extension methods.
Extension methods are associated with a class (either a specific one or they are generic and can work for any class). What makes them different from normal instance methods is that they are not defined within the class itself. Instead, they are defined in some other static class. This all sounds rather strange, so let’s take an example.
Imagine that we had got some third party class library for computing a serial number for a product from a product ID and some user details. The method may take the arguments ProductID, CustomerName, CustomerDateOfBirth, and CustomerCountry. In the class library, its implementation may look something like this:

public sealed class CodeGenerator
{
public long generateCode(int ProductID, string CustomerName, DateTime CustmerDOB, string CustomerCountry)
{
return (ProductID % 42) + CustomerName.GetHashCode() * (CustmerDOB.Ticks - CustomerCountry.GetHashCode());

}
}

In our application, however, we pass around user data in a structure.

struct UserInfo
{
public int UserID;
public string Name;
public DateTime DOB;
public string CountryCode;
}

Obj is used in two ways. The first is that it refers to the v-table. This can be used to look up the method to call (in the case of method overriding). The second use is that it is passed as the first parameter to the method. This parameter is taken and becomes the "this" variable – this is what the CLR does under the hood. So essentially, all of your instance methods have an implicit first parameter that the C# compiler inserts for you and provides access to through the "this" variable.

Second, there is an alternative way of thinking about object orientation: rather than having a class-based system, you can use multi-methods. Multi-methods are very similar to method overloading in C# - you can have methods with the same name but different signatures, and the right one is invoked depending on the parameters that are used in the call. Now imagine that the implicit first parameter that we just discussed is not implicit, but instead you place it at the start of every method's parameter list. The type of that first parameter can be a class name. When deciding which method to call, the full signature (including the type of the invocant – the first parameter) is taken into account. That means that you can write methods for a particular class anywhere you like in your program, or extend existing classes with your own methods.

Sometimes the object a method is being called on is referred to as the invocant. For example, in obj.method(), obj is the invocant.If you can get your head around those ideas, then you will find extension methods fairly straightforward. An extension method is a static method, but with the first parameter it takes being explicitly marked as receiving the object that the method was called on. Extension methods may only appear in static classes. Returning to our example, we can implement an extension method like this:

static class MyExtensions
{
public static long generateCode(this CodeGenerator CG, int ProductID, UserInfo User)
{
return 2 + 3;
}
public static long generateCode(this CodeGenerator CG)
{
return 2 + 3 + 4;
}

}

Now run the following code from your page load event
CodeGenerator CG = new CodeGenerator();
UserInfo User = new UserInfo();
User.UserID = 453;
User.Name = "Manab";
User.DOB = DateTime.Now;
User.CountryCode = "UK";


long Code = CG.generateCode(5183, "Manab", DateTime.Now, "UK");
long Code2 = CG.generateCode(5183, User);
long Code3 = CG.generateCode();
Response.Write(Code + "<br/>");
Response.Write(Code2 + "<br/>");
Response.Write(Code3 + "<br/>");

Output :
4605813284442487372
5
9

Another question that comes up is that of performance. Does the runtime have to locate the method to call at runtime, or is it worked out at compile time? The answer is that it is decided at compile time, so there is not any runtime dispatch overhead. In fact, the lookup doesn't even go through the v-table, so it may well be faster than some instance method calls. (For those who like to have the details, the .Net CLR provides an instruction, named "call", for calling a method without consulting the v-table, which the compiler can use instead of the standard one when it knows that it is safe to do so).

Perhaps the most important question, though, is when extension methods should be used. The C# designers themselves say that they are not something you want to be using all of the time, but rather in situations where instance methods are unable to provide what you need.

If you have a class and want to extend it with some special functionality that is specific to your usage of it, you now have two options.
Inherit from it and put the special functionality in the sub class
Write extension methods
The first option is preferable. Inheritance is well understood by other programmers, it is clear what method will be called and you won't have to repeatedly write the class name when writing the methods. So why the second option? I can think of a few cases.
If the class is sealed, you will be unable to inherit from it. In this case, you have no option but to use extension methods.
You may be using some kind of object factory that instantiates objects of a given class, but you do not have the ability to modify it so that your subclass is instantiated instead. Therefore extension methods are the only way to extend the functionality of these objects.
You want to implement a method that can be invoked on all classes implementing a given interface; before, we had no way to attach a method implementation to an interface.
You may want to add related things to a number of other classes, and from a software engineering point of view it may be better to collect those together in one place rather than spreading them amongst many classes.
If you find yourself writing extension methods every day, then that's probably a bad sign. It's a myth that every language feature is intended to be used equally often, both in real and programming languages.


A complete code is as follows.I have write this code in the aspx page of an Web application

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
public partial class CSharp3_ExtensionMethods : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CodeGenerator CG = new CodeGenerator();
UserInfo User = new UserInfo();
User.UserID = 453;
User.Name = "Manab";
User.DOB = DateTime.Now;
User.CountryCode = "UK";


long Code = CG.generateCode(5183, "Manab", DateTime.Now, "UK");
long Code2 = CG.generateCode(5183, User);
long Code3 = CG.generateCode();
Response.Write(Code + "<br/>");
Response.Write(Code2 + "<br/>");
Response.Write(Code3 + "<br/>");



A a1 = new A();
Response.Write("a1.useMe():" + a1.useMe() + "<br/>");

B b1 = new B();
Response.Write("b1.useMe():" + b1.useMe() + "<br/>");
Response.Write("b1.useMe(manab):" + b1.useMe("manab") + "<br/>");

A a2 = new A();
Response.Write("a2.useMe(manab) :" + a2.useMe("manab") + "<br/>");
}
}
struct UserInfo
{
public int UserID;
public string Name;
public DateTime DOB;
public string CountryCode;
}
public sealed class CodeGenerator
{
public long generateCode(int ProductID, string CustomerName, DateTime CustmerDOB, string CustomerCountry)
{
return (ProductID % 42) + CustomerName.GetHashCode() * (CustmerDOB.Ticks - CustomerCountry.GetHashCode());

}
}
static class MyExtensions
{
public static long generateCode(this CodeGenerator CG, int ProductID, UserInfo User)
{
return 2 + 3;
}
public static long generateCode(this CodeGenerator CG)
{
return 2 + 3 + 4;
}

}
//Create another example of extensions as belows
public class A
{
public string useMe()
{
return "I am in Class A ->useMe()";
}
}
public class B : A
{
/* public string useMe()
{
return "I am in Class B ->useMe()";
}*/
}
static class C
{
public static string useMe(this A a1, string str1)
{
return "I am in Class C ->useMe(this A a1,string str1)";
}
}
public class Jungle
{
public string Add(Monkey mn)
{
return mn.HelloMonkey();
}
}
public class Monkey
{
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string HelloMonkey()
{
return Name;
}
}

Output is as follows:

4605813284442487372
5
9
a1.useMe():I am in Class A ->useMe()
b1.useMe():I am in Class A ->useMe()
b1.useMe(manab):I am in Class C ->useMe(this A a1,string str1)
a2.useMe(manab) :I am in Class C ->useMe(this A a1,string str1)


tags:what is Extension Methods in C# 3.0/3.5,how can we implement Extension Methods in c# 3.0/3.5

C# 3.0 Tutorial -1:Var Keyword

Var keyword

you can now declare a veriable with the "var" keyword where you dont need to mention the datatype

var Hello = "hello Programmer";
var my number = 42;

At first glance, it appears that you’re declaring a variable of type “var”. Actually, "var" is not a type, but rather a new keyword that means, “I want to declare a variable, but I’m too lazy to write out its type”. For cases where the type is "Dictionary<int, List<int>>" or similar, this saves quite a bit of clutter in the code:
// Before:
Dictionary<int, List<int>> Coeffs = new Dictionary<int, List<int>>();
// After:
var Coeffs = new Dictionary<int, List<int>>();

Following is a code snippent of Var keyword (code is done within an aspx page of a WebSite application)

using System;
using System.Data;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class CSharp3_VarKeyword : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
/*var name = 22; name = "manab";//will throws error or var name;name="Manab"; will also throws error*/
var name = "Manab";
var answer = 42;
var prog = new DataSet();
var Friends = new List<string>();
var coeffs = new Dictionary<int, List<string>>();
var array = new[] {2,3,4,5,6,7 };
Response.Write("name is of type " + name.GetType().Name + "<br/>");
Response.Write("answer is of type " + answer.GetType().Name + "<br/>");
Response.Write("prog is of type " + prog.GetType().Name + "<br/>");
Response.Write("Friends is of type " + Friends.GetType().Name + "<br/>");
Response.Write("coeffs is of type " + coeffs.GetType().Name + "<br/>");
Response.Write("array is of type " + array.GetType().Name + "<br/>");
Response.Write("array element is of type " + array[2].GetType().Name + "<br/>");

bool condition = false;
var setCondionality =condition? new a():new b();
Response.Write("set Condionality is " + setCondionality.GetType().Name);
}

public class a { }
public class b :a{ }


}

And the output of the above prograp is as follows

name is of type String
answer is of type Int32
prog is of type DataSet
Friends is of type List`1
coeffs is of type Dictionary`2
array is of type Int32[]
array element is of type Int32
set Condionality is b


I consider that an improvement, both to developer productivity when writing code and to those reading the code too.

tags:what is var keyword in 3.0/3.5