The developer's guide to C# 2.0

 

Summary

C# 2.0 promises some impressive new tricks when it arrives later this year. This guide by Glenn Stephens is just the ticket you need to get started today.

Events

IBM Technology Conference & Expo 2012
May 23, 2012

Convention Centre B2 Room at 22nd Floor, Centara Grand @ Central World, 999/99 Rama I Road, Pathumwan, Bangkok 10330

Echelon 2012
June 11 and 12, 2012

University Cultural Centre, National University of Singapore

Startup Asia Jakarta 2012
June 7 and 8, 2012

12th Floor, Annex Building, Wisma Nusantara Complex, Jl. M.H. Thamrin No. 59 Jakarta 10350, Indonesia

MMA Forum Singapore
April 23-25, 2012

Grand Hyatt Singapore

C# 2.0 promises some impressive new tricks when it arrives later this year. This guide by Glenn Stephens is just the ticket you need to get started today.

The next version of the C# programming language, called C# 2.0 will ship as part of the Microsoft .NET Framework 2.0 and Visual Studio 2005 contains new language features that are designed to ease many typical developer problems. Some of these changes include generics, nullable types, iterators, static classes, anonymous methods, and partial classes.

This article will discuss the basics of these new language features and hopefully give you some insight on how they may best be used in your development efforts, kicking off with anonymous methods.

An Anonymous Admirer
For those of you familiar with Java, then you are probably already familiar with anonymous methods. Anonymous methods allow you to define a method’s implementation without defining a full method. For example, if you were assigning a Click event handler to a button, you may do something similar to Listing A.

Listing A
btnFirst.Click += delegate { MessageBox.Show(“Hi there”); };

In the original C#, you would have had to define a method handler for this by creating a method that performs an operation and then assign a delegate to the event. Most event handlers that you will use though will take parameters of some sort, and you can see that the code in Listing A does not deal with the parameters, however they can easily be assigned by placing the parameter definitions in the declaration (see Listing B).

Listing B
btnSecond.Click += delegate(object senderArgs, EventArgs ea)
{
MessageBox.Show(“The components type is “ +
senderArgs.GetType().Name);
};

As you can see creating anonymous methods is simple. It is especially helpful when you are dynamically creating controls and need to define the events for the newly created control, or anywhere where you need to manipulate delegates and events that have simple implementations.

Nullable Types
Do you work with databases? Chances are that you work with databases more than anything else, which would mean that at some time you have to deal with reading in a null value from a column. Most people adopt a convention for storing a null value such as -1 for an integer column or a blank string for a string column. Included in C# 2.0 is support for nullable types where a primitive data type can have a value stored in it but can also store a null value. Declaring a nullable type field/variable is the same as declaring a normal field or variable, however after the data type you place a question mark as shown in Listing C.

Listing C
int? ReportsToID;
private string ReportsToText()
{
if (ReportsToID.HasValue)
return “Employee Number “ + ReportsToID.Value;
else
return “No one”;
}

The field that I am using in Listing C is actually based on the Employee table from the developer-famous Northwind database where the ReportsToID column contains a reference to another employee if that employee reports to anyone, or null if that employee does not report to anyone. In the case of the ReportsToID column shown, either an integer value or the value of null can be assigned. Listing C also shows how you can access the value of the nullable type. Each nullable type has two properties, a Boolean property called HasValue to determine whether or not it contains a value and also the Value property which has the actual value.

Generics – C# 2.0’s sliced bread
Generics are a feature that you will see touted everywhere from Microsoft and in all areas of publications, and with good reason. Of all the features in C# 2.0, generics will have the greatest impact on the amount of code that you write.

So what are generics? Generics allow you to define type parameters to a class and are especially handy for collections of data or operations that are performed on any form of type. For example you may have a class of operations that work on any type or another class that stores a list of objects, but in C# 1.0 to make it work you would have to code implementations of each type for the first example, or in the collection example you would have to make sure that everything was cast to an object data type and have to continuously. When you wanted to access the object you would then need to do a type comparison to see that what you entered is the correct type.

Listing D demonstrates the code for a simple list generic class that allows you to work with a list of data types indexed by a single value. I am using this example as a demonstration of accessing a list of objects which would have a primary key.

Listing D
public class IndexedObjectFinder where T : IndexedObject, new()
{
Hashtable entries = new Hashtable();

public IndexedObjectFinder() { }

public void Add(object id, T entry)
{
entries[id] = entry;
}
public void Remove(K id)
{
entries.Remove(id);
}
public T GetEntry(K id)
{
return (T)(entries[id]);
}
public void Load(string sql, SqlConnection conn)
{
//Load all the suppliers from the database
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();

if (conn.State != ConnectionState.Open)
conn.Open();

da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
T entry = new T();
entry.Load(row);
Add(entry.Key, entry);
}
}
}

As you can see Generics treat types as parameters to the class definitions, and to declare a generic instance you declare the generic class with the types that will be used as shown in Listing E.

Listing E
IndexedObjectFinder SupplierList;
SupplierList = new IndexedObjectFinder();

As you can see when you declare the generic variable, you declare the types that the generic instance will use. Using Listing D as an example, the IndexedObjectFinder will now return a Supplier class from the GetEntry method and also take a Supplier instance as a parameter in the Add method. Generics give you the flexibility to always work with the data type that you specifically want at compile time. For this example, without generics you would have to define a base class for the collection and then continually subclass in order to get the desired type functionality. Generics without a doubt will be the language feature that will impact C# developers everywhere because it has the potential to save an extraordinary amount of time.

Iterators
A common task when developing collection classes is to implement the functionality to support the foreach operator. This is normally done by implementing the System.Collections.IEnumerable interface which can be a headache due to the amount of code needed to implement this interface. C# 2.0 greatly simplifies the implementation of the IEnumerable interface with the use of the yield keyword.

For example, to implement the iterator for the generic class we created earlier, we can use the code shown in Listing F.

Listing F
public class IndexedObjectFinder : IEnumerable
public IEnumerator GetEnumerator() {
foreach (object o in entries.Values)
yield return (T)o;
}

You can see from the example that all is required is for every entry in the collection, you call the yield return followed by the value that you are returning or alternativly call yield break which means that there are no more items in the collection.

You can see by the small amount of code in the above listing how this can dramatically help you develop code that deals with collections.

Partial Types
Partial Types allow you to split a class definition between several files. This has many potential benefits but mainly to do with the development process. You may for example be working with a large organisation and have several developers working on the one class. In original C# land, it is likely that you are working with Microsoft SourceSafe as a version control mechanism, which means that only one person will be able to write to that file at any given time, which meant you had to wait for the other developer to check the file back in, even if they were working in an area of that class totally unrelated to your area.

Another benefit of partial types is when it comes to code generation. I love to live in OO land where you have persistent mapping to an object, and much of this code is generated through my own custom tools. Normally I generate classes based on a table schema and generate the appropriate code there. The medications I normally make relate only to the methods of the class and not the properties. It would be much better for me to use my tool to generate a partial class which contains only the data types in one source file and then write my custom logic as part of the rest of the partial class in another source file.

To declare a partial class is straightforward. Before the class keyword in your class definition, place the keyword partial. You then repeat this for all the entries of this partial class and you are on your way. Listing G and Listing H both demonstrate the use of partial classes to create a loan repayment class where the fields are in one file and the methods to perform the operations are in another.

Listing G
public partial class LoanRepayment
{
public double amount;
public double interestRate;
public int numberOfPayments;

public LoanRepayment(double Amount,
double InterestRate, int NumberOfPayments)
{
this.amount = Amount;
this.interestRate = InterestRate;
this.numberOfPayments = NumberOfPayments;
}
}

Listing H
public partial class LoanRepayment
{
public double CalculateInterest()
{
return Amount * Math.Pow(1 + InterestRate, NumberOfPayments);
}
}

It is worth noting that partial classes can also be used on structs and interfaces, so just as you place the partial keyword before the class definition you also put it before the interface or struct keywords.

Static classes
The last feature I will talk about is the static class, which is a nice addition to the C# language. When you have a class that only contains static methods or constant values, you would normally not want to create an instance of this class, so often this class is declared as sealed and does not have a public constructor, so the constructor is declared as private. Rather than ensuring that the classes is sealed and has a private constructor, in C# 2.0 you simply declare the class as static and it implies this, there are some caveats, however: you cannot have a static class have a base class, it cannot be declared sealed or abstract, you cannot have protected declarations and the class can only contain static methods, constants and nested types.

Conclusion
There are some great new features in C# 2.0. While some changes such as static classes or partial classes are minor but still significant, other changes such as generics and iterators will save you a great deal of time making you even more productive by having to write less code.

Talkback

Isn't all that obvious from Microsoft specs.

Static classes have been existing in OO world for a long time now. Generics also have been existing in C++ (from the STL library) world for around 10 years.

I would have expected a more innovative and in depth research statement.

Just Replying October 17, 2005
Add your opinion

In order to post a comment, you need to be registered. (Sign In or register below)

Post your comment

ZDNet Asia Live

Big data acquisitions pave way to fast, effective innovation - ZDNet Asia News http://t.co/vDZpl0lu

"Big data acquisitions pave way to fast, effective innovation" including @Vivisimo_Inc (client) in @ZDnetAsia http://t.co/yNSdPqbb

Homegrown smartphone OSes gaining favor in China: 59 Jakarta 10350, Indonesia Locally-made mobile operating syst... http://t.co/BruP98Es

RT @MDMGeek: Big data acquisitions pave way to fast, effective innovation - ZDNet Asia http://t.co/ky8YgPAn #Bigdata #analytics via @ciropuglisi

Integration, focused investments to propel Windows Phone http://t.co/6JkDa9sB

RT @AsianFashionLaw: Malaysia offers some manufacturing benefits over China http://t.co/bMquIFiX

Acquisitions in the Big Data market increasingly important to enterprises… http://t.co/Br4BkXyZ

Experience trumps content in apps monetization http://t.co/iaCY5ebX

Malaysia offers some manufacturing benefits over China http://t.co/bMquIFiX

RT @MDMGeek: Big data acquisitions pave way to fast, effective innovation - ZDNet Asia http://t.co/ky8YgPAn #Bigdata #analytics via @ciropuglisi

Thats it.Im digging up an old bus plan i wrote around acquisition of #bigdata talent. http://t.co/gpkha5A1 Any investors want2 read/discuss?

Integration, focused investments to propel Windows Phone: By Kevin Kwang , ZDNet Asia on May 23, 2012 (2 mins ag... http://t.co/aaa0Cb73

Homegrown smartphone OSes gaining favor in China http://t.co/lOBVp1T6

Homegrown smartphone OSes gaining favor in China: 59 Jakarta 10350, Indonesia Locally-made mobile operating syst... http://t.co/gHypbdIY

Integration, focused investments to propel Windows Phone - ZDNet Asia http://t.co/7sZi6Dhb

So much as we know , MTK6575 extremely integrated frequency1GHz ARM Cortex-A9 processor, the superiority of 3G / HSPA Modem, and help the...

1 day ago by y15822137359 on 5 SaaS adoption speed bumps to avoid

I reckon your view: "CRM is strategy, not software", if a company replicating the approach uses in ERP implementation into CRM, what they...

2 days ago by wykoong on Gartner: Mobile CRM gives better ROI than social

This video will teach you about the Excel fill handle but also provide you with a workook to download... http://www.youtube.com/watch?v=...

3 days ago by TradeBrother on A quick fill handle trick for Microsoft Excel

waiting...

5 days ago by eapete on What should count in a company's market value?

Boy, you've opened a can of worms now.

Wait for the rants & raves.

5 days ago by eapete on What should count in a company's market value?

I was puzzling before this whether to replicate the success formula we executed for a financial institute, and come out with a standard s...

5 days ago by wykoong on Drop the egos, copy ideas, then innovate