We have begun introducing generics into all of our code at work and I have found it difficult to understand, lots of 's and this sort of thing and when you multiply that across all of the project I have decided I need to get a grip on generics in C#.
My port of call was the Microsoft MSDN website, and that is what I am looking at now allthough I have 2 books as well, Beginning C# 2005 (Wrox Press) and C# In depth (Skeet).
My first question was what is the benefits of generics, I managed to survive without them before. Luckily one of the articles on the MSDN website answers this directly http://msdn.microsoft.com/en-gb/library/b5bx6xee.aspx
Obviously this article doesn't answer all of the questions it just addresses using list over arraylist however it is a start. What I hadn't realised was that when you use an arraylist is casts everything you add to the array into the object type which is both performance hungry and also allows you to run the chance of a run time error.
For example the website uses
System.Collections.ArrayList list = new System.Collections.ArrayList();
// Add an integer to the list.
list.Add(3);
// Add a string to the list. This will compile, but may cause an error later.
list.Add("It is raining in Redmond.");
int t = 0;
// This causes an InvalidCastException to be returned.
foreach (int x in list){ t += x;}
Here you would not want to be mixing to different types but if you used a generic list instead the error would have been flagged up immediately.
My port of call was the Microsoft MSDN website, and that is what I am looking at now allthough I have 2 books as well, Beginning C# 2005 (Wrox Press) and C# In depth (Skeet).
My first question was what is the benefits of generics, I managed to survive without them before. Luckily one of the articles on the MSDN website answers this directly http://msdn.microsoft.com/en-gb/library/b5bx6xee.aspx
Obviously this article doesn't answer all of the questions it just addresses using list
For example the website uses
System.Collections.ArrayList list = new System.Collections.ArrayList();
// Add an integer to the list.
list.Add(3);
// Add a string to the list. This will compile, but may cause an error later.
list.Add("It is raining in Redmond.");
int t = 0;
// This causes an InvalidCastException to be returned.
foreach (int x in list){ t += x;}
Here you would not want to be mixing to different types but if you used a generic list instead the error would have been flagged up immediately.
Comments