Skip to content

Instantly share code, notes, and snippets.

@jjokela
Created August 10, 2014 20:09
Show Gist options
  • Save jjokela/b4a1518ad01798da93f0 to your computer and use it in GitHub Desktop.
Save jjokela/b4a1518ad01798da93f0 to your computer and use it in GitHub Desktop.
C# Generics sample
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleGenericsTest
{
/// <summary>
/// Generic registration class
/// </summary>
/// <typeparam name="T">Type to register</typeparam>
public class Register<T>
{
private List<T> _list = new List<T>();
public void Add(T input)
{
_list.Add(input);
}
public void Print()
{
foreach (var item in _list)
{
Console.WriteLine(item.ToString());
}
}
}
/// <summary>
/// Simple registrar class
/// </summary>
public class Registrar
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
class Program
{
static void Main(string[] args)
{
// registers some registrars and prints them
Register<Registrar> registrars = new Register<Registrar>();
registrars.Add(new Registrar { Name = "Risto Reipas" });
registrars.Add(new Registrar { Name = "Erno Perälä" });
Console.WriteLine("Registrars: ");
registrars.Print();
Console.WriteLine();
// I can also register ints or other types if I like...
Register<int> ints = new Register<int>();
ints.Add(1);
ints.Add(2);
ints.Add(3);
Console.WriteLine("Ints: ");
ints.Print();
Console.ReadLine();
// Outputs:
/*
Registrars:
Risto Reipas
Erno Perälä
Ints:
1
2
3
*/
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment