Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created December 12, 2016 22:33
Show Gist options
  • Save DominicFinn/7f5c54ac1a170e58ded0f4624434d61f to your computer and use it in GitHub Desktop.
Save DominicFinn/7f5c54ac1a170e58ded0f4624434d61f to your computer and use it in GitHub Desktop.
A little example of generics and how they might be used.
using System;
using System.Linq;
using System.Collections.Generic;
namespace Generics
{
/// <summary>
/// We use the interface to describe how an animal should be behave, anything that is an IAnimal has to conform to these specs
/// </summary>
public interface IAnimal
{
void Walk();
void Eat();
void Drink();
string Name { get; }
}
/// <summary>
/// Dog is an IAnimal
/// </summary>
public class Dog : IAnimal
{
string name;
public Dog(string name)
{
this.name = name;
}
public string Name { get { return name; }}
public void Drink()
{
}
public void Eat()
{
}
public void Walk()
{
}
}
/// <summary>
/// Cat is an IAnimal
/// </summary>
public class Cat : IAnimal
{
string name;
public Cat(string name)
{
this.name = name;
}
public string Name { get { return name; } }
public void Drink()
{
}
public void Eat()
{
}
public void Walk()
{
}
}
public class FunWithAnimals
{
/// <summary>
/// An Example of being able to use both Cats and Dogs together because they both confirm to the IAnimal interface
/// </summary>
/// <returns>The and dogs.</returns>
public IList<IAnimal> CatsAndDogs()
{
return new List<IAnimal>()
{
new Dog("Hoochy"), new Dog("Spot"), new Cat("Puffles")
};
}
/// <summary>
/// Gets the name of an IAnimal, where we say T, we mean an object, the where bit at the end of the method is
/// called the Generic Constraint, it's where we say whatever object we put in the place of T must be an IAnimal
/// </summary>
/// <returns>The name.</returns>
/// <param name="animal">Animal.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public string SayHelloToAnimal<T>(T animal) where T : IAnimal
{
return "Hello " + animal.Name;
}
/// <summary>
/// Put together the methods above, first we get a list of cats and dogs, then we use the Linq, select extension method and
/// call SayHelloToAnimal on each one... We can treat them all as IAnimals and be guarenteed that we get a name off each one
/// </summary>
/// <returns>The of cats and dogs.</returns>
public IEnumerable<string> NamesOfCatsAndDogs()
{
return this.CatsAndDogs().Select(animal => this.SayHelloToAnimal(animal));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment