Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomkuijsten/65487760a28b14a4df39ab0bbbe1e170 to your computer and use it in GitHub Desktop.
Save tomkuijsten/65487760a28b14a4df39ab0bbbe1e170 to your computer and use it in GitHub Desktop.
Sample of c# override keyword
using System.Collections.Generic;
using System.Linq;
using System;
public static class Program
{
public static void Main()
{
var dogs = new List<Dog>();
dogs.Add(new Dalmatier());
dogs.Add(new Terrier());
foreach (var dog in dogs)
{
dog.Bark();
}
Console.WriteLine("");
foreach(var dog in dogs)
{
dog.AngryBark();
}
Console.WriteLine("");
foreach(var dog in dogs)
{
dog.Sleep();
}
Console.WriteLine("");
foreach(var dog in dogs.OfType<Dalmatier>())
{
dog.Sleep();
}
}
}
public abstract class Dog
{
/// <summary>
/// Every dog Barks in a different way, abstract forces an implementation
/// </summary>
public abstract void Bark();
/// <summary>
/// Default dogs do the same bark just twice in a row when they are angry
/// </summary>
public virtual void AngryBark()
{
Bark();
Bark();
}
/// <summary>
/// All dogs have the same sleep sound, no virtual or abstract necessary.
/// </summary>
public void Sleep()
{
System.Console.WriteLine("Zzzzzzzz");
}
}
public class Dalmatier : Dog
{
public override void Bark()
{
System.Console.WriteLine("Waf");
}
/// <summary>
/// A Dalmatier makes a really weird sleep sound
/// </summary>
public new void Sleep()
{
System.Console.WriteLine("Grrnnnnrzzzz");
}
}
public class Terrier : Dog
{
public override void Bark()
{
System.Console.WriteLine("WOEF");
}
/// <summary>
/// An angry Terrier has a special bark
/// </summary>
public override void AngryBark()
{
System.Console.WriteLine("GRRRRRR WAF");
System.Console.WriteLine("GRRRRRR WAF WAF");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment