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 ~

ADO.NET Data Service in Plain English

I have been using ADO.NET Data Service in Silverlight since Astoria team released the client library for Silverlight. I didn’t have a particular idea to use that service except this is something new that I like to try. After reading a few article about Astoria, I come to know that I can retrieve the data from Astoria service by typing the URL in browser. And we have to use the different HTTP verbs for CRUD operations. That’s all? I think “No”. So, I raised a question in MSDN forum last week. Today, I got very useful and informative reply from Mike Flasko. (Thanks a lot for your reply, Mike.)

Here is the original thread that I posted in MSDN forum. Now, I’m here to share this information with you all. Hope that you will find it useful.

Question : What is ADO.NET Data Service (Astoria)?

Hello,

Could anyone please explain me about ADO.NET Data Service in plain english without using marketing term?

AFAIK,
– we can query the data by typing URL in browser.
– it supports CRUD operations with different HTTP verb.

But I believe that there might be some important reasons why people created this framework.

  • What is the ADO.NET Data Service?
  • What are the advantages of using ADO.NET Data Service?
  • What’s wrong with Web service?
  • What is the reason why making differnt HTTP verb for CRUD operation?

Thanks in advance.
Michael Sync

Answer from Mike Flasko (Astoria Program Manager [MSFT] )

Hi Michael,

In general the goals of ADO.NET Data Services are to create a simple REST-based framework for exposing data centric services. We built the framework in part from analysis of traditional websites and then looked at how architectures were changing with the move to AJAX and RIA based applications. One key observation the team had was that in traditional approaches to web development the information exchanged between a client (ex. a webbrowser) and the mid tier was a combination of presentation + behavior + data (ex. HTML file with javascript and inline HTML tables of data) and that the core interactions to retrieve raw data was between the mid-tier and backend store (ex. SQL server or other). When we looked at RIA, AJAX, smart client, etc applications it became apparent that these architectures pushed much more “smarts” to the client tier where the client first retrieves the presentation + behavior information (as a DLL in the case of a Silverlight application) and then as the user interacts with the client application, the app turns back (ex. background async call) to the mid-tier to retrieve the data needed to drive the user experience. This is nothing new (separation of presentation + behavior from data), but its interesting to note it now not only a best practice but mandated in the architectures of today’s web and RIA apps. From this we looked at how such clients could consume data from the mid-tier today and how could we help improve the experience for the developer. A few areas came up:

  • Creating and maintaining rich data oriented services with current approaches requires a significant developer investment
  • Building generation purpose client libs/tools with current approaches to data centric services is hard

For #1, imagine you wanted to expose the data in your CRM database to you client tier application. Further assume you want to enable typical application scenarios like retrieving sorted views of the data, paging over the data, filtering, etc. To expose this data as a set of callable remote methods (using current approaches to developing web services) you would need to write a large number of methods to expose each of the entities in your CRM DB (customers, orders, etc) and then add additional methods for each to retrieve entities by key, sort them, page over them, etc etc. ADO.NET Data Services, addresses this issue by allowing you to declaratively state the contract of such a data centric service, by telling us the schema of the data and having the data services technology automatically create the required remote endpoints, enabling paging, sorting, etc with no code from the developer. Then as you change your data model, your service endpoints also change.

For #2 above, an interesting artifact of a REST-based approach to web services is that it promotes creating a uniform interface. That is, how you address items in an ADO.NET Data Service (i.e. how to construct URIs), how to interact with data (using HTTP verbs), etc is the same across any ADO.NET Data Service, regardless of the data it exposes. This uniform interface enables code reuse against your web services such that one can create reusable client libraries and UI widgets for all their services. For example, the ADO.NET Data Service team is doing this by shipping .NET , Silver light, AJAX, etc libraries which can talk to any data service. In addition, this feature (uniform interface) enables us to add features such as LINQ to ADO.NET Data Services since the translation of LINQ query statements to URIs is stable and well known.

This is already probably a bit too long Smile, but in addition to the items noted above, additional advantages of REST-based approaches also apply such as rich integration with HTTP such that you can leverage existing HTTP infrastructure (ex. HTTP Proxies) deployed at large …

I hope that helps….
~ Mike

Here are a few links for those who don’t know about REST Service.  

Hope you find it useful.
Related ~