12/6/2006 4:24:31 PM
I am probably behind the class on this but in scoping out a new project I realized that I would be using the System.Collections namespace. After learning that I could use the 2.0 framework I started looking at the System.Collections.Generic namespace instead. I then fired up Visual Web Developer and started creating a mock-up of what will be a huge component of the application I am to develop and played with some Generics.
Lately I have heard a lot about C# Generics. Andrew Robinson told me that once I started using Generics in the 2.0 Framework I would not have a reason to go back to 1.x. He was right. In just a couple of minutes I was realizing how convenient Generics can be.
Old World (Non-Generic)
protected void Page_Load(object sender, EventArgs e)
{
foreach (DictionaryEntry de in NonGenericDictionary())
Response.Write(de.Key + ", " + de.Value + "<br />");
int five = (int)NonGenericDictionary()[5];
int six = (int)NonGenericDictionary()[6];
int eleven = (five + six);
Response.Write(eleven.ToString());
}
private
Hashtable NonGenericDictionary()
{
Hashtable hashtable = new Hashtable();
hashtable.Add(5, 5);
hashtable.Add(6, 6);
return hashtable;
}
New World (Generic)
protected void Page_Load(object sender, EventArgs e)
{
foreach (KeyValuePair<int, int> kvp in GenericDictionary())
Response.Write(kvp.Key + ", " + kvp.Value + "<br />");
int one = GenericDictionary()[1];
int two = GenericDictionary()[2];
int three = (one + two);
Response.Write(three.ToString() + "<br />");
}
private Dictionary<int, int> GenericDictionary()
{
Dictionary<int, int> dictionary = new Dictionary<int, int>();
dictionary.Add(1, 1);
dictionary.Add(2, 2);
return dictionary;
}
Due to the simplicity of these two examples one would probably not notice any performance gains or losses. I have read that some refuse to believe that working with Generics is more convenient or efficient than non-Generics. I haven't even scratched the surface of usefulness and I would already beg to differ. Using Generics means stronger type-checking. Errors are never exciting but in my opinion it is much better to find errors during compile-time instead of down the road at run-time. You will also write much less code. Gone are the days of writing multiple methods to handle different datatypes. Now code is much more elegant (and quicker) to write when using one method that can operate on several data types.
I look forward to Generics and hopefully this project will help me in becoming schooled in the trade.
.NET,
C#,
Code

Comments

I am getting more and more interested about .NET but i am an absolute newbie in this language. I know c++ and a little bit of Java. If i learn Java better will i be able to perform ok in C# ?
Posted by: donate car | 4/2/2007 4:44:07 AM