Archive for C#

C# 3.0 Tutorials: What is Anonymous type?

This is my fourth part of my C# 3.0 tutorials. We have finished learning about automatic properties that introduces new and shorter way of creating the properties, object and collection initializer that gave us the way to initialize the object or collection in shorter and cool way, implicitly typed local variables that can be declared without specifying the type explicitly. I told you that implicitly typed local variables and anonymous type are the best match but I didn’t mention anything about Anonymous type in previous tutorial. Now, it is the time we start discussing about anonymous type which is introduced in C# 3.0.

What’s Anonymous type?

Anonymous type is the type that is created anonymously. Anonymous type is a class that is created automatically by compiler in somewhere you can’t see directly while you are declaring the structure of that class. Confusing? Let me show you one example.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
Person _person = new Person { ID = 1, FirstName = "Michael", LastName = "Sync" };
Console.WriteLine("Name: {0} {1}", _person.FirstName, _person.LastName);
Console.ReadLine();
}
}
public class Person {
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}

Please take a look at the code above. I created a class called Person that has three properties such as ID, FirstName and LastName. In Main() function, I declared a variable and initialized the properties of the instance. Yes. this is just a normal way of creating a class and initializing the instance that we have been doing this for years.

Now, I will change the normal class to anonymous type.
Anonymous types

The first thing that you need to do is that remove the class. (C# compiler will create the anonymous class based on what you initialize with.) Secondly, we have to change _person variable to implicitly-typed local variable by replacing “Person” with “var”. Because we have removed Person class from our code so that we won’t know about the type. That’s why the variable “_person” should be declared as a implicitly-typed local variable. Then, we will remove “Person” after “new” keyword.

So, our final code will be like that below ~


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
var _person = new { ID = 1,
FirstName = "Michael",
LastName = "Sync" };

Console.WriteLine("Name: {0} {1}",
_person.FirstName,
_person.LastName);

Console.ReadLine();
}
}
}

It’s just like using object and collection initializer. but the magic comes at this point. The C# compiler will create the anonymous class based on the initializer in IL. You can’t see/access that class directly from code but you should know there is a class.

Now, I think that you understand what Anonymous types are and how to create them. But there is one important must-known thing left to tell you. Keep in mind that you can create the Anonymous type as the way that I showed above but this is NOT what it is designed for.

Let me share you one nice comment from this link.

I think that perhaps your dislike of C#’s new features stems from the fact that you are looking at the new features and trying to imagine how you would use them within the context of your current programming patterns. However, these new features are designed to be used in completely new ways.

Anonymous types are not meant to be used in places where you would care about their name or method overriding — in those cases you should use a class. Anonymous types are for when you want to just group together a bunch of data items. Perhaps you are running a query that returnsa few arbitrary pieces of data, or maybe you have a function that needs to return multiple pieces of data. Can you imagine what it would be like if you had to create a new class for each different query in an application?

C# 3.0’s new set-based operators (LINQ) give us wonderful new tools for working with data sets. One thing we frequently need is objects which do nothing besides hold data to iterate over. Do you want to define a datatype for every query that returns a different set of columns? Quite frankly, it’s a pain in the butt. It leads to a proliferation of meaningless types, type unsafety (just using objects), or somewhere inbetween (having a bunch of standard types and only filling in whatever data is returned because maintaining the types every time a query changes becomes too much work).

The type proliferation problem is especially bad in Java where each class requires its own file. As a side note, I once wrote a compiler for a language with lexical scoping (like Pascal, where a function could have an inner function that can access the local variables of its outer function). This means that each local variable scope requires its own separate data structure, which would have to have its own separate class file if the compiler were targeting the JVM. What’s the point of having a whole bunch of classes with no methods and every member public?

internal class CustomerName_OrderCount { public string Name; public int Count; }
internal class CustomerName_Country { public string Name; public string Country; }
internal class CustomerName_Country_State_Phone { public string Name; public string Country; public string State; public string Phone; }
internal class CustomerName_Country_State_Phone_OrderCount { public string Name; public string Country; public string State; public string Phone; public int Count; }

I wouldn’t want an unnecessary mess like that cluttering up my code.

Additionally, though, having anonymous types means that the compiler knows that calling the constructor and properties have no side-effects, which allows it to reason about the values in ways it otherwise could not. This is important for being able to translate queries to SQL and know that you’re getting the correct semantics.

I really like this comment and it did explain a lot. Anonymous types are designed for LINQ. If you are very new to LINQ then you might feel those C# 3.0 features are not so cool but once you got that then you will just love them. :)

Let’s take a look the practical way of using Anonymous type with LINQ ~

We have one XML file as following structure and data.


<?xml version="1.0" encoding="utf-8" ?>
<Girls>
<Girl>
<Name>Camilla Belle</Name>
<DateOfBirth>October 2, 1986</DateOfBirth>
</Girl>
<Girl>
<Name>Megan Fox</Name>
<DateOfBirth>May 16, 1986</DateOfBirth>
</Girl>
<Girl>
<Name>Vicki Zhao(Zhao Wei)</Name>
<DateOfBirth>March 12, 1976</DateOfBirth>
</Girl>
<Girl>
<Name>Kelly Hu</Name>
<DateOfBirth>February 13, 1968</DateOfBirth>
</Girl>
<Girl>
<Name>Elisha Cuthbert</Name>
<DateOfBirth>November 30, 1982</DateOfBirth>
</Girl>
<Girl>
<Name>Alicia Silverston</Name>
<DateOfBirth>October 4, 1976</DateOfBirth>
</Girl>
<Girl>
<Name>Christy Chung</Name>
<DateOfBirth>September 19, 1970</DateOfBirth>
</Girl>
</Girls>

You can easily query the data from this XML with the code below. Additionally, you will get the strong-typed variable reference. That means you will see “Name” and “DateOfBirth” as the properties of “Girl” class in intellisense.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
XDocument xmlSource = XDocument.Load("Girls.xml");

var girls = from g in xmlSource.Descendants("Girl")
select new
{
Name = g.Element("Name").Value,
DateOfBirth = g.Element("DateOfBirth").Value
};

foreach (var girl in girls) {
Console.WriteLine("Name: {0}, Date Of Birth: {1}",
girl.Name,
girl.DateOfBirth);
}
Console.ReadLine();
}
}
}

Yes. This is what Anonymous type, implicitly-typed variables and object initializer are designed for. They are so powerful and very cool with LINQ. I hope that you now have good understand about what Anonymous type is and how to use it. You should play around with your own scenario or use it in your real project if you have the chance so that you will be more familiar with those new features and will understand more than what I wrote in this tutorial. Good Luck. :)

C# 3.0 Tutorials: Implicitly typed local variables

This is the third article of C# 3.0 tutorial series. We will take a look the first feature called “Implicitly typed local variables declaration” in this article.

What is Implicitly typed local variable?

Implicitly typed local variable is a variable that can be declared without specifying the .NET type explicity. The type of that variable will be inferred by the complier from the expression on the right side of initialization statement.

Let me show you the simplest sample of “Implicitly typed local variable”. Let’s think about the way that we declare the variable in C#. Normally, we used to declare the variable with a specific type, right? For example: int i = 1; In implicitly typed variable declaration, you don’t need to write “int”. You don’t need to set that the type of variable “i” is integer type. Instead, you can use the brand new C# 3.0 keyword “var” in that place. So, the code will be like that. “var i = 1;” As the value that assigned to “i” variable is 1, the type of “i” variable will be Integer automatically.

“var” is not like object or varient type that has expensive cost. That type of that variable will be changed to the actual .NET type based on what value you have assigned to that variable. As I mentioned in example above, if you assign 1 to i, the type of i will be integer data type.
Let’s open Visual Studio 2008 and create one C# console application. then, open the Program.cs and type the following code in Main().


var i = 1;

then, type “i” “.” (dot) and check-out the intellisense. You will see it as the screenshot below. Then, try to declare the int variable (let’s say “j”) in normal way and check what you have in intellisense for that new integer variable “j”. You will get exactly the same thing like what you get for variable “i”, the implicitly type local variable. That means variable “i” become integer type based on the value that we initialize.

Implicitly typed local variable

Fig: 1.0: the variable "i" as integer data type.

Okay. Let’s change the initialized value of variable “i” from 1 to “This is a string”.


var i = "This is a string";

Then, type “i” “.” (dot) and check-out the intellisense again. What you saw in intellisense is changed now. (You can compare both screenshots.) The type of variable “i” has been changed since we have changed the value “1″ to “This is a string” in declaration. So, you can think of “var” as a place holder where the compiler will replace the real data type based on what you initialize the variable.

Implicitly typed local variable

Fig: 1.1: the variable "i" as string data type.

This is the basic things about implicitly typed local variable. You can declare any kinda data type as I mentioned in the example below.


var i = 5;
var s = "Hello";
var d = 1.0;
var numbers = new int[] {1, 2, 3};
var orders = new Dictionary<int,Order>();

Restrictions

Before you start using the implicitly type variables, you should know that there are a few restrictions of using that type of variables. (Ref: C# 3.0 Specification)

  1. The declarator must include an initializer.Unlike normal declarations, you can’t declare the implicitly type variable without initializing. For example: The following code won’t be complied.
    
    var test; // ERROR: Implicitly-type local variable must be initialized.
    
  2. The initializer must be an expression. The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer.You can’t initialize it with an array. For example ~
    
    var test =  { 1, 2, 3 }; //Error    1    Cannot initialize an implicitly-typed local variable with an array initializer
    //Error    2    Can only use array initializer expressions to assign to array types. Try using a new expression instead.var test1 = new[] { 1, 2, 3 }; //This is correct!!
    
  3. The compile-time type of the initializer expression cannot be the null type.
    
    var test =  null; //ERROR
    
  4. If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type.The implicitly-type local variable cann’t be initialized with different types more than one time. You can’t assign the string to varaible “test” after initializing with integer value “1″.
    
    var test = 1;
    test = "This is a string"; // ERROR
    

FAQs

Whenever I discussed with a few developers about that type of variables, they used to ask me the following questions.

Q #1: Why do we need to use “var” when we can declare the variable with real data type?

A #1: Yes. You don’t need to use “var” if you know what type you want to use. This is not what it is designed for. If you know the type then use the type.

Q #2: Let’s say I wrote like that “var myvar = 1;”. then, C# compiler will assume my variable “myvar” is int, right? Actually, I declared it as long.. How can I make the compiler to know my variable “myvar” is long data type. What about “int vs uint”, “long vs ulong” and “double vs float vs decimal”??

A #2. Initially, I also had that doubt in my head. ( Thanks to Codeproject members who cleared that doubt from my mind.) Actually, this is the variation of previous question. Even though you can declare as the code below, you should not use it because as I told you earlier, if you know the type then use that type.


var ui = 1U; // uint
var l = 42L; // long
var big = 1234567890UL; // ulong
var pi = 3.1416; // double
var size = 12.5F; // float
var price = 27.99M; // decimal

Conclusion

What I would love to say for conclusion is that ~

  • The implicitly typed local variables is not an object or variant.
  • “var” is just like a placeholder where the compiler will replace the actual datatype based on what you initialize with.
  • You shouldn’t use implicitly-typed local variable if you know the type.
  • “Implicitly-typed local variables” are the best things to use when you are dealing with anonymous type or LINQ.

Thanks.

C# 3.0 Tutorials: Object and Collection Initializers

Howdy everybody! This is the second part of my C# 3.0 tutorial series in my blog. Today, we are gonna talk about object and collection initializers, one of the features of C# 3.0.

This feature allows you to initialize the entity object or collection in very easy way that we’ve never done before. When I was working for .NET 1.1 or 2.0 projects, I used to create at least three constructors in each and every entity classes just for making rich-constructors that helps the developers to initialize easily.

For example ~


public class Cat {
#region private variable declaration
private int _catID;
private string _name;
#endregion

#region constructors
public Cat() {
}
public Cat(string name) {
_name = name;
}
public Cat(int id, string name) {
_catID = id;
_name = name;
}
#endregion

#region properties
public int CatID{
get{
return _catID;
}
set{
_catID = value;
}
}

public string Name{
get{
return _name;
}
set{
_name = value;
}
}
#endregion

}

The reason why I created those constructors is that it make the developer’s life easier to initialize the object as below.


Cat cat = new Cat(1, "Pepsi Ko");
Cat anotherCat = new Cat("Ordico");

but just imagine that what if we have 100 entity classes with 20 or more properties. Creating three constructors for those classes would be time-consuming process, isn’t it? if you are a project manager of the team, you can simply ask your developers to add those constructors in each entity class. but sometime, you don’t have that level of control all the time. then, you will end-up writing the code below.


Cat cat = new Cat();
cat.CatID = 1;
cat.Name = "Pepsi Ko";

Cat anotherCat = new Cat();
anotherCat.Name = "Ordico";

With C# 3.0, you don’t need to write those constructors and you don’t need to ask anyone to create the constructors for you. You can simply initialize the object as below ~


Cat cat = new Cat { CatID = 1, Name = "Pepsi Ko" };
Cat anotherCat = new Cat { Name = "Ordico" };

It’s pretty cool, isn’t it? It saves some of your typing time and copy-n-paste works. :) If you are using VS 2008, you will get cool intellisense that can tell you what properties you have initialized.

VS Intellisense for Object Initializer

VS Intellisense for Object Initializer

If your entity class has the object of another class as a field then you can also initialize the contained class as below.

Let’s say you have the class like below ~


public class Cat {
public int CatID { get; set; }
public string Name { get; set; }
public List<Cat> Children { get; set; }
}

then, you can initialize like below ~


Cat mamamCat = new Cat { CatID = 1, Name = "Pepsi Ko",
Children = new List<Cat>{
new Cat{ CatID =11, Name = "Pussy Lay" },
new Cat{ CatID =12, Name = "Kitty" },
new Cat{ CatID =13, Name = "Soemasoe" }
}
};

All right. This is all about object and collection initializer. The advantage of using this feature is that it save some of your time for creating a lot of constructors or initializing the individual property. That’s all. If you have any comment or suggestion, please let me know. Thank you!

C# 3.0 Tutorials: Auto-Implemented Properties (a.k.a Automatic Properties)

Note: This is the first part of my C# 3.0 tutorial series.

Auto-implemented properties is the C# 3.0 new feature that make property-declaration more concise. It helps you to save some of your time for typing a lot of codes. Please take a look the following code to know how it looks like.


class Car
{
public string Speed { get; set; }
}

Why Auto-Implemented Properties?

Looking back the way that we have been doing for creating a property in so many projects, do you notice that you have been writing so many line codes just for creating a simple property? Look at the code below.


public class Employee {
private int _id;
private string _firstName;
private string _lastName;

public int ID{
get{
return _id;
}
}

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

public string LastName {
get {
return _lastName;
}
set {
_lastName = value;
}
}
}

Code 1.0: Employee class that doesn’t use auto-implemented properties

This is what we used to create the property in C#. In order to create one simple property, we have to type extra four or five lines of code. So, if you have one hundred properties in different entity classes, you have to type toooo much code just for creating properties.

I think VS IDE team at Microsoft also awared of this situration. That’s why when they released Visual Studio 2005 with .NET framework 2.0, we got the better way to deal with creating properties. You can simply type “prop” and press “tab” key twice. then, VS IDE will generate the property for you. Or you can use “Encapsulate Field” from “Refactor” menu to create the property. Unfortunately, those features are available only in C# project type in VS 2005. If you are using VB.NET project, you won’t be able to use that feature.

And when Microsoft shipped .NET framework 3.0, the new feature called “Auto-Implemented Properties (a.k.a Automatic Properties)” is introduced in Framework 3. It helps you to save some of your typing time for declaring private variable, setting the value to that private variable and returning the value.

Take a look at the class that I have converted from normal class (Code 1.0) to the class with auto-implemented properties. It’s much shorter, right?


class Employee
{
public int ID{ get; private set; } // read-only
public string FirstName { get; set; }
public int LastName { get; set; }
}

Code 1.1: Employee class that uses auto-implemented properties

Conclusion

Auto-Implemented Properties is one of the most popular features of C# 3.0 and a lot of developers are really happy with that new feature. but you should know that auto-implemented properties are nothing new except it helps you to boost your productivity.

FAQs

1. Can “Auto-implemented Properties” improve the performace?

No. It is just helping you to type shorter code but it doesn’t improve the performance since the compiler will generate the same as the way what it generates for normal class that doens’t have auto-implemented properties.

2. How can I make read-only or write-only auto-implemented properties?

You can make the accessor as private. For example: If you want to make read-only property then You can put “private” in setter. You can read more about that in C# 3.0 specification.

It mentioned like below in C# 3.0 specification ~

When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field.

Because the backing field is inaccessible, it can be read and written only through the property accessors. This means that automatically implemented read-only or write-only properties do not make sense, and are disallowed. It is however possible to set the access level of each accessor differently. Thus, the effect of a read-only property with a private backing field can be mimicked like this:


public class ReadOnlyPoint {
public int X { get; private set; }
public int Y { get; private set; }
public ReadOnlyPoint(int x, int y) { X = x; Y = y; }
}

Okay. This is all about Auto-Implemented Properties (a.k.a Automatic Properties). If you have any suggestion or comment, please drop a comment in this post. Thank you!

C# 3.0 Tutorials with Visual Studio 2008 for Beginners

I have been doing C# 3.0 for a while now but I never wrote any tutorial related to C# 3.0 in my blog before. So, I decided to write a few C# 3.0 tutorials while I’m waiting the release of Silverlight 2.0 beta 1. I also notice that some of my friends from Silverlight Forum are so silent lately and they don’t even so active in the forum. I know that they are busy with preparing to go to MIX08 or learning WPF/Media/Flash/Flex.

In this tutorial series, I will cover the following topics with full of explanations, sample and etc (like my other tutorials in my blog). This tutorials are dedicatedly written for those who already have some experiences with C# 1 or 2 and totally newbie for C# 3.0. You will need to install Visual Studio 2008 to run the sample code.

Topics

The links will be updated once I published the tutorial in my blog. Please feel free to let me know if you want me to add something or if you have the suggestion or comment.

You can subscribe my feed if you used to read the blog through feed reader. OR, you can give me your email here then I will inform you if I post new tutorial in my blog. (Of course, I promise that I won’t share your mail with anyone and I won’t be spam you. You will have to activate your mail after putting your email address in this link.)

SEAMonster: Intelligent Image Resizing Tool

SEAMonster is the open-source .NET-based implementation of seam carving. Seam carving is an image resizing algorithm developed by Shai Avidan and Ariel Shamir. What that algorithm does is that it changes the dimension of image by intelligently removing pixels from (or adding pixels to) the image. If you are very interested in this algorithm, you may read it here or download this pdf file (20 MB).

Download : Executable or Sourcecode

SEAMonster Logo

You can watch the power of SEAMonster tool or how Seam Carving algorithm in the video below.

Video 1.1 : Seam Carving for Content-Aware Image Resizing

I noticed that tool since Mike Swanson, technical evangelist at Microsoft, wrote about this in his blog. (SEAMonster: A .NET-Based Seam Carving Implementation). I will write about how to use this tool in next article.

Related ~