Created
April 30, 2012 17:29
-
-
Save jcreamer898/2560294 to your computer and use it in GitHub Desktop.
Generics for Geriatrics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var movies = new Library<Movie>(); | |
movies.Collection.Add(new Movie | |
{ | |
Id = 1, | |
Name = "A New Hope" | |
}); | |
movies.Collection.Add(new Movie | |
{ | |
Id = 2, | |
Name = "Empire Strikes Back" | |
}); | |
movies.Collection.Add(new Movie | |
{ | |
Id = 3, | |
Name = "Return of the Jedi" | |
}); | |
var movie = movies.Find(3); | |
Console.WriteLine("Best of Star Wars is..." + movie.Name); | |
var books = new Library<Book>(); | |
books.Collection.Add(new Book | |
{ | |
Id = 1, | |
Name = "Fellowship of the Ring" | |
}); | |
books.Collection.Add(new Book | |
{ | |
Id = 2, | |
Name = "The Two Towers" | |
}); | |
books.Collection.Add(new Book | |
{ | |
Id = 3, | |
Name = "Return of the King" | |
}); | |
var book = movies.Find(2); | |
Console.WriteLine("Best of LOTR is..." + book.Name); | |
} | |
} | |
class Movie : ICollectible | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
class Book : ICollectible | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
interface ICollectible | |
{ | |
int Id { get; set; } | |
string Name { get; set; } | |
} | |
class Library<T> where T : ICollectible | |
{ | |
public List<T> Collection { get; set; } | |
public Library() | |
{ | |
Collection = new List<T>(); | |
} | |
public T Find(int id) | |
{ | |
return Collection.Single(i => i.Id == id); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment