Getting Ready for .NET 3.5 and LINQ – Exploring C# 3.0 – Part I

Posted by: Manish Sharma , on 10/29/2008, in Category C#
Views: 119385
Abstract: C# 3.0 introduces several language enhancements that are built on C# 2.0. The changes enables the construction of a style that is equally powerful as query languages; generally used to fetch data from relational database management systems and XML files. If you are gearing up to get started with LINQ, then this article is for you. It also serves as a refresher to those who are already familiar with the new features of C# 3.0
Getting Ready for .NET 3.5 and LINQ – Exploring C# 3.0 – Part I
 
Microsoft released its IDE i.e. Visual Studio 2008 (Codename: Orcus) along with a new framework i.e. .Net 3.5 in November 2007. Along with the new framework, came new versions of languages such as C# 3.0 and VB.Net 9 and some new features for Web developers as ASP.NET 3.5.
 
C# 3.0 introduces several language enhancements that are built on C# 2.0. The changes enables the construction of a style that is equally powerful as query languages; generally used to fetch data from relational database management systems and XML files.
 
If you are gearing up to get started with LINQ, then this article is for you. It also serves as a refresher to those who are already familiar with the new features of C# 3.0
 
The changes made in C# 3.0 are as follows:
 
•   Local Variable Type Inference or Implicitly Typed Local Variables.
•   Object Initializers
·         Collection Initializers
·         Anonymous types
·         Auto-implemented properties
•   Extension methods
•   Lambda expressions
·         Query expressions
•   Expression trees
·         Partial Methods
 
This is a two part article which tells you about the changes which are made in C# 3.0. In this Part (Part I) we are going to see the first five of the above given changes.
 
It will be noticeable after reading the article (Part I and Part II) that the changes which are made in C# 3.0, is because Microsoft wanted to give developers, an efficient way(LINQ) for fetching data from the data stores (objects, datasets, SQL or XML) in a more declarative way rather than the imperative way.
 
So let’s start:
 
Local Variable Type Inference
 
          The concept of local variable type inferences sometimes termed as ‘Implicitly Typed Local Variables’ is there with Microsoft from long. The variant type in Visual Basic and C++ (when using the Component Object Model) as well as “var” keyword in JavaScript is the base for this change.
 
C# 3.0 offers a new keyword called "var", that allows a developer to declare a variable without explicitly declaring the type of it. For example:
 
   var data = 1;
 
By seeing the above mentioned line, one would wonder about type safety.
 
Even though ‘var’ allows you to implicitly do the declaration, it does not eliminate the type safety. This means that ‘var’ is used only at the time of declaration and with the declaration you have to specify some value or some expression to it. And soon as you have done it the type is assigned and after that you cannot change the type of value that variable is holding.
 
For instance, the following code will throw a compile time error:
 
   var data = 1;
   data = 23.4f;                //Compile time Error
 
Interestingly ‘var’ can be used in any of the following ways:
 
Directly associating a value or type:
 
   var data1 = 10;             // data1 is of type System.Int32
   var data2 = 20.5f;          // data2 is of type System.Single
   var data3 = "Hello";        // data3 is of type System.String
   var data4 = new List<int>(); // data4 is of type Generic List<T>
   var data5 = new CEmployee(); // data5 is an instance of Class CEmployee
 
Associating with expressions:
 
     var data6 = 23 + 45;         // data6 is of type System.Int32
 
Association with methods:
 
In C# 2.0, if you want to call a method ( GetData( ) ) which returns you an integer, you will write something like this:
 
     int data = GetData();
 
and if GetData() returns you a string, the above written line will throw an error, but now with ‘var’ you can write the same code as follows:
 
     var data = GetData();
 
Now even if your GetData() method returns you any type, the above written line need not be changed.
 
There are some rules associated with ‘var’, which are as follows:
 
1.    You must initialize ‘var’ type variables with some value or expression.
 
2.    Once the type is assigned to ‘var’ type variable you cannot change the type of value the variable holds.
 
3.    ‘var’ cannot be used as a return type of the methods.
 
var Add(int x,int y);              //Error
 
4.    ‘var’ cannot be used in argument list of the methods.
 
int Add(var x,var y);              //Error
 
5.    The contextual keyword 'var' can only appear within a local variable declaration         i.e. ‘var’ types can be created only inside a method or a block.
 
Object Initializers
 
This change in C# 3.0 allows developers to get rid of the constructors they have to write in case of C# 2.0. Say for example in C# 2.0 if you have a class named CEmployee as follows:
 
   class CEmployee
   {
        private int EmpID;
        public int EID
        {
            get { return EmpID; }
            set { EmpID = value; }
        }
 
        private string EmpName;
        public string ENAME
        {
            get { return EmpName; }
            set { EmpName = value; }
        }
   }
Now, if you want to initialize the objects at the time of declaration, as follows:
 
   CEmployee obj1 = new CEmployee(101, "Manish Sharma");
   CEmployee obj2 = new CEmployee(102);
   CEmployee obj3 = new CEmployee("Abhijeet Gole");
 
To write the code shown in the lines above, the developer should write three parameterized constructors inside the CEmployee class as follows:
 
   public CEmployee(int id, string name)
   {
        EmpID = id;
        EmpName = name;
   }
 
   public CEmployee(int id)
   {
        EmpID = id;
   }
 
   public CEmployee(string name)
   {
        EmpName = name;
   }
 
However in C# 3.0, if you have created properties inside your class as in above given CEmployee class, you do not have to write the constructors anymore. So C# 3.0 gives you this enhancement to write it easily as follows:
 
   CEmployee obj1 = new CEmployee() { EID = 102, ENAME = "Abhijeet Gole" };
   CEmployee obj2 = new CEmployee() { EID = 103 };
   CEmployee obj3 = new CEmployee() { ENAME = "Ramakant Debata" };
 
The above given lines of code are easier to read in respect with C# 2.0 code, but you have to write a bit more code.
 
Collection Initializers
 
With C# 3.0, Collection Initializer is the combination of Collection Classes and Object Initializers. This feature is available for all the objects which are enumerable (i.e. they implement IEnumerable<T>) and have a public ‘Add’ Method to add the values.
 
Remember the CEmployee class used in the above feature i.e.
 
   class CEmployee
   {
        private int EmpID;
        public int EID
        {
            get { return EmpID; }
            set { EmpID = value; }
        }
 
        private string EmpName;
        public string ENAME
        {
            get { return EmpName; }
            set { EmpName = value; }
        }
   }
 
Using the above given class, if you want to create a List of Employees, then in C# 2.0 the code will be:
 
   List<CEmployee> Employees = new List<CEmployee>();
   CEmployee e1 = new CEmployee(101, "Manish Sharma");
// If you have  implemented Constructor
   Employees.Add(e1);
 
And, if there is no Constructor, then:
 
   List<CEmployee> Employees = new List<CEmployee>();
   CEmployee e1 = new CEmployee();
   e1.EID = 1;
   e1.ENAME = "Pravin Dabade";
   Employees.Add(e1);
 
This is for 1 Employee, now if you want to add 5 Employees, then you have to create them separately and add them in the list one by one.
 
But in C# 3.0, it is made easier, like below:
 
   List<CEmployee> Employees = new List<CEmployee>()
   {
        new CEmployee() { EID = 101, ENAME = "Abhijeet Gole" },
        new CEmployee() { EID = 102, ENAME = "Manish Sharma" },
        new CEmployee() { EID = 103, ENAME = "Mithilesh Sonkusare" },
        new CEmployee() { EID = 104, ENAME = "Pravin Dabade" },
        new CEmployee() { EID = 105, ENAME = "Ramakant Debata" }
   };
 
           
Anonymous Types
 
C# 2.0 gave us Anonymous methods which are declared inline and had no formal name, in the same way C# 3.0 gives Anonymous Types which are created with the help of combining ‘var’ (Local Variable Type Inference) and Object Initializers as follows:
 
      var cust = new { CustID = 101, CustName = "Manish" };
 
For the above given code, C# compiler automatically generates a name. Each member of the type i.e. CustID and CustName are the properties taken from the syntax of Object Initializer.
 
The actual place where we can use Anonymous types will be given in Part II when we will discuss LINQ.
 
Auto-Implemented Properties
 
In my opinion, this is one of the productive changes in C# 3.0 which makes your code more readable without writing more lines for implementing properties. In C# 2.0, we implement properties with get and set accessors for returning (get) a private member’s value and for setting (set) a private members value, like as follows:
 
   class Customer
   {
        private string customerID;
        public string CustomerID
        {
            get { return customerID; }
            set { customerID = value; }
        }
 
        private string contactName;
        public string ContactName
        {
            get { return contactName; }
            set { contactName = value; }
        }
 
        private string city;
        public string City
        {
            get { return city; }
            set { city = value; }
        }
   }
 
So, in the above code you have declared three properties, every time doing the same thing i.e. returning and setting a private members value, which reduces the readability of the code.
 
But in C# 3.0 the same pattern can be implemented in a better way like follows:
 
   class Customer
   {
        public string CustomerID { get; set; }
        public string ContactName { get; set; }
        public string City { get; set; }
   }
 
For the above given code C# Compiler will automatically generate backing fields.
 
But there is a limitation i.e. when we use this kind of syntax for implementing properties we have to implement both get and set accessors.
 
Whereas we can use modifiers today also with Auto implemented properties i.e. you can have properties as follows:
 
   public string CustomerID { get; private set; }
 
Conclusion
 
In this article, we explored the first five new features introduced in C# 3.0. I hope you found the content useful and I thank you for viewing it. Stay tuned as in Part two, we will explore the rest of the changes in C# 3.0.
 
Manish Sharma, PGDCA, MCA, is a Freelance consultant. Manish has over 8+ years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) and has conducted various Public Batches & Corporate Training programs in all .NET Technologies.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Author bio not available


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Jay on Thursday, October 30, 2008 9:27 AM
Very nice introduction. thanks,
Comment posted by Manish Sharma on Thursday, October 30, 2008 11:57 AM
Thanks Jay
Comment posted by Dilbert on Friday, October 31, 2008 1:55 AM
Anonymous Types could be explained further with an example. Otherwise, good article.
Comment posted by Pravin Dabade on Friday, October 31, 2008 1:57 AM
Hi Manish,

This is really a nice document which will let you know the Changes between C# 2.0 to C# 3.0.
Comment posted by aejeit on Tuesday, November 4, 2008 12:25 AM
Thanks for the article
Comment posted by kk18_b on Monday, November 10, 2008 10:55 PM
Good Intro.
Comment posted by solairaja on Tuesday, December 2, 2008 3:16 AM
hi manish,
Nice article simple but very useful one.
plz post some advanced concepts of C# 3.0 (for realtime usage)

thanks in advance
Comment posted by heaiping on Wednesday, December 3, 2008 9:20 AM
thinks ! how about the C# 4.0?
Comment posted by Venkateswarlu.M on Friday, December 5, 2008 1:03 PM
Good Notes
Comment posted by Muhammad Haroon on Thursday, January 15, 2009 9:21 AM
This is really nice Intro where is the second part of this article! Thanks
Comment posted by Mazher Alee on Monday, January 26, 2009 1:47 AM
I agree with Dilbert comments and Where is the 2nd part ?
Comment posted by Manish Sharma on Monday, February 9, 2009 1:10 AM
Sorry was very busy with my training schedules, so was not able to post the II part, will be posting it in the coming week or so.
Comment posted by Jass on Monday, February 9, 2009 9:12 PM
Ok thanks..waiting for part 2.
Comment posted by Sarath on Wednesday, May 13, 2009 11:47 PM
Excellent ground work keep it up waiting for the second part
Comment posted by kumar on Sunday, May 31, 2009 4:51 AM
nice article manish http:://www.planetsourcecode.in
Comment posted by kumarnit on Wednesday, June 17, 2009 10:36 AM
nice article manisa
Comment posted by Jyoti G on Monday, July 20, 2009 5:30 AM
Gr8 Article
Comment posted by Deepali Kamatkar on Wednesday, August 19, 2009 6:34 AM
very informative and "to the point"
Comment posted by Ajay Narang on Monday, August 16, 2010 7:00 AM
Good Summarized view
Comment posted by selva on Saturday, May 7, 2011 12:18 AM
very good article
Comment posted by dfdf on Tuesday, October 30, 2012 4:21 AM
ddf
Comment posted by Sanghamitra on Wednesday, January 30, 2013 12:18 AM
Very enlighting article. Thanks!
Comment posted by Saurabh on Sunday, August 4, 2013 10:02 PM
good article. all codes are easy to understand. thanks :)
Comment posted by suneetha on Monday, August 4, 2014 3:53 AM
Thank you very much
Comment posted by Ramsuhavan Patel on Thursday, August 7, 2014 9:59 AM
excellent work.