Chapter 9 – Generics

SAMS CSHARP 4.0 (Page 156)

* Create a Generic List

user List<T> to create a list of T type objects.

class Person {
public string Name {get; set;}
public string Address {get; set; }
};

static void Main(string[] args) {
List<Person> people = new List<Person>();
// declare a list of Person-typed objects
people.Add(new Person() {Name=”Bruce”, Address=”4007 BB Lane”});

Person p = people[0]; . // No casting is needed
}

*** Use Generics instead of ArrayList can avoid boxing and unboxing.

* Create Generic Method

You need a method that can be called to perform the same work on different types of arguments.

define a generic method:

private static void Sawsp<T> (ref T a, ref T b) {
T temp = a;
a = b;
b = temp;
}

to call this method:

Swap<int> (ref aInt, ref bInt); or
Swap<string> (ref aString, ref bString); or

* Create a Generic Interface

//declare generic interface of T

interface IUnique<T> {
T Id { get; }
}

//implement interface with specific types
class MyObject : IUnique<int>
{
private int _id;
//implementation of interface’s method
public int Id
{
get { return _id; }
}
}

class MyOtherObject : IUnique<string> {
private string _id;
public string Id
{
get { return _id; }
}
}

TUPLES – New in C# 4

Group multiple values (can be different type) together and use them together.

Example 1:

example 2: (practical use)

Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: