Skip to content

Instantly share code, notes, and snippets.

@Frank-Buss
Created April 1, 2020 10:54
Show Gist options
  • Save Frank-Buss/dec1ca008ce17b65eecc12d38bca31cc to your computer and use it in GitHub Desktop.
Save Frank-Buss/dec1ca008ce17b65eecc12d38bca31cc to your computer and use it in GitHub Desktop.
using "dynamic" in C# to call overloaded methods
using System;
using System.Collections.Generic;
abstract class Tile
{
}
class SeaTile : Tile
{
}
class SkyTile : Tile
{
}
class Program
{
static void CreateGui(SeaTile tile)
{
Console.WriteLine("sea tile");
}
static void CreateGui(SkyTile tile)
{
Console.WriteLine("sky tile");
}
static void Main(string[] args)
{
// generic list with the base class
var tiles = new List<Tile>();
// add two specific objects
tiles.Add(new SeaTile());
tiles.Add(new SkyTile());
// use "dynamic" to create a variable with the type of the actual object for each iteration
foreach (dynamic tile in tiles)
{
// call the specific overloaded method
CreateGui(tile);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment