sábado, 23 de maio de 2009

Generics - A great addition to .Net

Ver este post em Portugûes

Hello. In this post I'll show something very nice about .Net: Generics.

First, I'll show a simple struct in order to explain the feature:


struct Person {
public string Name;
public string Address;
public string Zip;
}


We have here a classic example of a data struct. Here we define fields with their respective data types (we're talking here about a strongly typed language). That means we have to provide the data type of the attributes at compile time. But, what if we could let the (struct's) user define what type s/he wants to use in their struct? How so? e.g.: A struct, two fields and their data type is open to the user to specify and set the attribute, making it "appear" a weakly typed language, but with the advantage of type checking at compile time.

Let's take a look at an example:


struct Pair<TClass1, TClass2>
where TClass1 : class
where TClass2 : class {

public TClass1 obj1;
public TClass2 obj2;
}


Here comes the generics: We define a struct, asking the user to provide which clases will will represent the TClass1 and TClass2, which we are defining that have to inherit the class object and it automatically defines what data type that fields inside will accept

The nice part is when we start to use this structure. Let's see another code block:


class Customer {
public int ID;
public string Name;

public override string ToString() {
return string.Format("Customer ID = {0}, Name = {1}", ID, Name);
}
}

class Product {
public int ID;
public string Name;

public override string ToString() {
return string.Format("Product ID = {0}, Name = {1}", ID, Name);
}
}

struct Pair<TClass1, TClass2>
where TClass1 : class
where TClass2 : class {

public TClass1 obj1;
public TClass2 obj2;
}

class Program {
static void Main(string[] args) {

var c = new Customer { ID = 1, Name = "Felipe" };
var p = new Product { ID = 1, Name = "Caneta BIC" };

var pair = new Pair<Customer, Product>() { obj1 = c, obj2 = p };

Console.WriteLine(pair.obj1.ToString());
Console.WriteLine(pair.obj2.ToString());

}
}


The braces after the new instanct are a new notation of C# that allows us to create new instances of classes and set values to public fields in the same instruction.

In the progem we create instances of Customer and Product and define these types as the relevant types for the struct Pair. Note that, after we define the struct with these types we can only inform instances of these types for the specific fields. The compiler doens't let us inform any other value; and even the IntelliSense indicates correctly.

I hope you all liked this post and again, sorry for my english, as I am no native English speaker. Thank you very much and see you next time.

Nenhum comentário:

Postar um comentário

 
BlogBlogs.Com.Br