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.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!