Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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