Created
April 1, 2020 10:54
-
-
Save Frank-Buss/dec1ca008ce17b65eecc12d38bca31cc to your computer and use it in GitHub Desktop.
using "dynamic" in C# to call overloaded methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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