What are C# Generics - Part III

by agrace 24. April 2008 18:57

Panama Hat Personally, I think I am still in the process of making the final paradigm leap to generics. It will probably be some time yet before I am satisfied that I am applying the concept creatively enough in the early design phase. The end goal is to become comfortable enough with the new syntax to "genericize" my code and make it more type-safe and reusable overall.

Right now, a lot of people are overly-occupied with the latest 3.5 toys. If it ain't SilverLight or MVC it ain't worth talking about. It pays to concern oneself with the basic building blocks that make up the language of your choice. In my case, it is C# although I used C++ right through college and spent some time with Java. The point is that in an object-oriented world, such concepts as generics travel quite well across languages and underpin the development of a strong object view of things overall. The "drag and drop brigade" frequently have a problem grasping this.

Generic IL and Metadata

Nitty Gritty

Generics operate at the compiler level. It was necessary to change the metadata, compiler and IL instructions to make it all posssible. The upshot is that generics work across different .NET managed languages. This means that we can define a generic class in C# and consume it in VB. Score another one for code reuse :-)

Under the hood, the compiler generates the intermediate language (IL) which contains placeholders for the actual types which will be substituted at runtime. In other words, the generic types are "instantiated" at runtime. This is known as "lazy" specialization or "just-in-time". The accompanying metadata is used for compile-time type-checking and intellisense.

It is possible that code could try to use types which are not compatible with what was intended and "contraints" are provided as a measure of protection to prevent this happening. Remember, a generic class or method knows nothing about the arguments being passed to it. The compiler needs to know something more. Each type parameter can have a different set of constraints, expressed using a where clause. A parameter can have multiple constraints, separated by commas.

class Guitar < T1, T2, T3>
    where T1: Fender
    where T2: Gibson
    where T3: Martin

To recap, you will most likely find a use for generics with collections. It is well worth the time invested. Right now, I'm working my way through a copy of Professional .NET 2.0 Generics by Tod Golding. It's about the best book on the topic of Generics that I have come across. Happy coding!

kick it on DotNetKicks.com   PHP, ASP, .NET, JSP Resources, Reviews

Tags: ,


What are C# Generics - Part II

by agrace 11. April 2008 20:49

Generics I'm going to keep this as simple as possible. Your main goal is to gain an appreciation of why we would want to use generics in the first place. The typical candidate scenario for the use of generics is where we have a class that has a member variable, and the type of this variable should be defined by the client of the class, and not by the programmer. Likewise, for a method that has a parameter passed to it. In other words, the code in our classes and methods remains the same and the types of the data can change with each use. Think code reuse.

Up to now, this type of generality involved writing the same code over and over for each type you wanted to accomodate. And with collections, you would typically have to use the object class and then cast back. This would involve boxing and unboxing for value types, which would incur heavy performance hits, depending on the size of your collections. More importantly, when casting back, you could not be certain of the type in the collection. This could result in runtime errors after your code had shipped. More than anything else, the type safety afforded by generics is its biggest selling point. Type-safe code is the easiest code to maintain, plain and simple.

With generics, we declare type-parameterized code which we can instantiate with different types. We write the code with '<T>' placeholders for types and then plug in the actual types when we are creating an instance. We don't have to use the letter 'T', it's just convention.

// 1.1 Loosely-Typed Collection
Class Stack
  public object Pop();

Stack s = new Stack();

// Cast necessary
int i = (int) s.Pop();

// 2.0 Strongly-Typed Collection
Class Stack<T>
  public <T> Pop();

Stack<int> s = new Stack<T>();

// No cast necessary
int i = s.Pop();

You'll probably find the most ready use for generics when implementing collections. The generic collection classes are part of the C# 2.0 System.Collections.Generic namespace. Below is a list of the traditional 1.1 collections and their new 2.0 equivalents (from Krzysztof Cwalina):

Non-Generic Similar Generic Type
ArrayList List<T>
Hashtable Dictionary<TKey,TValue>
SortedList SortedList<TKey,TValue>
Queue Queue<T>
Stack Stack<T>
IEnumerable IEnumerable<T>
ICollection N/A (use IEnumerable<T> or anything that extends it)
N/A ICollection<T>
IList IList<T>
CollectionBase Collection<T>
ReadOnlyCollectionBase ReadOnlyCollectionBase<T>
DictionaryBase N/A (just implement IDictionary<TKey,TValue>)
N/A SortedDictionary<TKey,TValue>
N/A KeyedCollection<TKey,TItem>
N/A LinkedList<T>

In the next part, I'll try and cut through the jargon attached to generics and also discuss some practical uses for generics in everyday coding tasks. In the meantime, check out this excellent Overview of Generics in the .NET Framework.

kick it on DotNetKicks.com   PHP, ASP, .NET, JSP Resources, Reviews

Tags: ,


What are C# Generics - Part I

by agrace 9. April 2008 21:10

Generic Breakfast They say the best developers are lazy. I used to believe this and would cite code reuse as justification for my inertia! For a long time now, I have been intending to use generics and collections more in my code. I guess I meant well, but in the real world we tend to go for what we know works and a syntax that we feel comfortable with. There are so many new additions to the C# langauge now that it is tempting to want to jump in and play. However, I feel that a grasp of generics is an important skill to acquire first. So, I'm going to take a walk through the generics landscape and see how it all fits together...

Here's a loose definition from a Microsoft MSDN article: "Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. In concept, generics are similar to C++ templates, but are drastically different in implementation and capabilities."

Generics Generics permit us to write code where the data types aren't hard-coded. If we have a lot of code that performs the same function but on different types, then we can get big savings in terms of performance and the amount of code that we actually have to create.

Let me say two things about generics right off the bat: first, the main motivation for generics is not one of performance. Performance is more of a side effect, if you will. It is more about what the name implies, that is, it gives a level of generality to our types. It helps us to factor out the behaviour of our classes from the data upon which they act. In addition to performance gains, we profit from increased code reuse and type safety. Second, although they share a similar motivation, generics and templates are fundamentally different animals: generics are created at runtime by the CLR and templates are created at compile time by the compiler.

The designers of generics define it as "a feature that permits classes, structures, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate." The goal of this series is to demystify generics and to encourage you incorporate it into your own code, even if only in a very basic way to begin.

In the next part, we'll take a look at some specifics including where we can use generics and and how to find our way through the new terminology associated with generics. We'll save 'Parametric Polymorphism' for a later installment ;-)

kick it on DotNetKicks.com   PHP, ASP, .NET, JSP Resources, Reviews

Tags: ,