Skip to content

Instantly share code, notes, and snippets.

@josephbk117
Created January 11, 2018 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save josephbk117/887337b87bcbb571254d2a754191df6a to your computer and use it in GitHub Desktop.
Save josephbk117/887337b87bcbb571254d2a754191df6a to your computer and use it in GitHub Desktop.
An exmple of generics in c#
using System;
using System.Collections;
using System.Collections.Generic;
public interface IUseMagic
{
void UseMagic();
}
public class MagicUser : IUseMagic
{
private string userName;
public MagicUser(string name){userName = name;}
public void UseMagic(){Console.WriteLine(userName + " used magic");}
}
public class Node<T> where T : IUseMagic
{
private Node<T> next;
private T data;
public Node(T t)
{
data = t;
}
public T GetData(){ return data; }
public Node<T> GetNext(){ return next; }
public void SetNext(Node<T> node){ next = node; }
}
class Program
{
static void Main()
{
Node<MagicUser> k = new Node<MagicUser>(new MagicUser("Jackie Chaaan"));
Node<MagicUser> k2 = new Node<MagicUser>(new MagicUser("Micheal Juksun"));
Node<MagicUser> k3 = new Node<MagicUser>(new MagicUser("Hawri Pouteur"));
Node<MagicUser> k4 = new Node<MagicUser>(new MagicUser("Fan Boi Chau"));
k.SetNext(k2);
k2.SetNext(k3);
k3.SetNext(k4);
Node<MagicUser> cur = k;
while(cur != null)
{
cur.GetData().UseMagic();
cur = cur.GetNext();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment