Click here to Skip to main content
15,884,298 members
Articles / Programming Languages / C#
Article

Duck Typing with the Dynamic Keyword

Rate me:
Please Sign up or sign in to vote.
4.72/5 (36 votes)
24 May 2013CPOL1 min read 44.6K   35   24
Don't do this at home.

Introduction

Disclaimer:

Kids, don't do try at home.  Yes, we're using keywords and classes you can easily find in the cupboards of your .NET language, but please do not mix these keywords as described here.  Potentially lethal (to your job and someone else's sanity) will result.  The programming you are about to witness has been done by a professional, stunted developer. 

Now, let's go blow up some of your dull ideas about programming!

One of the interesting things about languages like Ruby is Duck Typing, the "if it walks like a duck, if it talks like a duck, if you're yard is covered in duck s***, why then, it must be a duck!"  Of course, with strongly typed languages like C#, we just couldn't do some of the abusive amazing things you will see in weakly typed languages.  Instead, we've had to rely on object-oriented concepts like inheritance, polymorphism, and interfaces to achieve some small degree of coolness. 

But no more!  The world has become the playground of all things that go quack in the night with the advent of the "dynamic" keyword!

The Shackles Of Strong Typing...

Oh, the boring things we have to do for the sake of strong typing:

public interface IQuack
{
  void Talk();
}

public class Duck : IQuack
{
  public void Talk() {Console.WriteLine("Quack");}
}

public class Goose : IQuack
{
  public void Talk() { Console.WriteLine("Honk"); }
}

How They Bind Us, Constrain Us...

static void Speak(IQuack bird)
{
  bird.Talk();
}

IQuack bird1 = new Duck();
IQuack bird2 = new Goose();
Speak(bird1);
Speak(bird2);

Quack
Honk

But Free Us From The Shackles of Your Interfaces...

public class DynoDuck
{
  public void Talk() { Console.WriteLine("Dyno-Quack!"); }
}

public class DynoGoose
{
  public void Talk() { Console.WriteLine("Dyno-Honk!"); }
}

And We Become Free Men (and Women, and Birds)! 

static void Speak(dynamic d)
{
  d.Talk();
}

dynamic dynoBird1 = new DynoDuck();
dynamic dynoBird2 = new DynoGoose();
Speak(dynoBird1);
Speak(dynoBird2);

Dyno-Quack!
Dyno-Honk!

And Free of All Constraints Of Race, Creed, or...Class!

static void Speak(dynamic d, string outWithIt)
{
  d.Talk(outWithIt);
}

static dynamic InMyImage(string method, Action<string> action)
{
  dynamic dyn = new ExpandoObject();
  ((IDictionary<String, Object>)dyn)[method] = action;
  return dyn;
} 

To Soar with the Gods!

var actor = (Action<string>) ((mySpeech) => Console.WriteLine(mySpeech));

dynamic dyn1 = InMyImage("Talk", actor);
dynamic dyn2 = InMyImage("Talk", actor);

Speak(dyn1, "Rise, my fellow ducks!");
Speak(dyn2, "To Canada or bust!"); 

Rise, my fellow ducks!
To Canada or bust! 

And Like Icarus, To Crash Back To Earth

As we realize freedom comes with a price: complete coding chaos! 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Interacx
United States United States
Blog: https://marcclifton.wordpress.com/
Home Page: http://www.marcclifton.com
Research: http://www.higherorderprogramming.com/
GitHub: https://github.com/cliftonm

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Duncan Edwards Jones29-Jul-15 20:41
professionalDuncan Edwards Jones29-Jul-15 20:41 
GeneralMy vote of 1 Pin
Craigoose3-Jun-15 2:42
Craigoose3-Jun-15 2:42 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA13-Jun-13 20:39
professionalȘtefan-Mihai MOGA13-Jun-13 20:39 
QuestionMy Vote of 5 Pin
Keith Barrow3-Jun-13 0:15
professionalKeith Barrow3-Jun-13 0:15 
AnswerRe: My Vote of 5 Pin
Marc Clifton3-Jun-13 2:01
mvaMarc Clifton3-Jun-13 2:01 
GeneralRe: My Vote of 5 Pin
Keith Barrow3-Jun-13 2:16
professionalKeith Barrow3-Jun-13 2:16 
GeneralMy vote of 5 Pin
AlphaDeltaTheta1-Jun-13 2:45
AlphaDeltaTheta1-Jun-13 2:45 
GeneralMy vote of 4 Pin
Mohammed Hameed1-Jun-13 1:25
professionalMohammed Hameed1-Jun-13 1:25 
GeneralMy vote of 5 Pin
Leukocytes30-May-13 1:57
Leukocytes30-May-13 1:57 
GeneralMy vote of 5 Pin
dbrenth29-May-13 7:52
dbrenth29-May-13 7:52 
Questionamusing and useful Pin
BillW3329-May-13 4:13
professionalBillW3329-May-13 4:13 
GeneralMy vote of 5 Pin
Rick-Z28-May-13 4:01
Rick-Z28-May-13 4:01 
GeneralMy vote of 5 Pin
hawk6627-May-13 20:38
hawk6627-May-13 20:38 
GeneralMy vote of 5 Pin
Scott Burkow27-May-13 5:34
Scott Burkow27-May-13 5:34 
GeneralMy vote of 5 Pin
KChandos25-May-13 5:59
professionalKChandos25-May-13 5:59 
And so we have the genesis of the bird flu ...

... or the makings of a game of good 'ol duck-duck-goose.

Thank you for the entertainment, it was fun!
QuestionHilarious-knowelege Example! 5-o-5 Pin
prathameshpitale24-May-13 18:46
prathameshpitale24-May-13 18:46 
AnswerRe: Hilarious-knowelege Example! 5-o-5 Pin
prathameshpitale24-May-13 18:49
prathameshpitale24-May-13 18:49 
GeneralRe: Hilarious-knowelege Example! 5-o-5 Pin
Marc Clifton25-May-13 1:53
mvaMarc Clifton25-May-13 1:53 
GeneralOnly a quack would think duck typing is a good idea Pin
PIEBALDconsult24-May-13 11:55
mvePIEBALDconsult24-May-13 11:55 
GeneralRe: Only a quack would think duck typing is a good idea Pin
Marc Clifton24-May-13 12:02
mvaMarc Clifton24-May-13 12:02 
GeneralRe: Only a quack would think duck typing is a good idea Pin
PIEBALDconsult24-May-13 13:34
mvePIEBALDconsult24-May-13 13:34 
GeneralMy vote of 5 Pin
BadassAlien24-May-13 10:40
professionalBadassAlien24-May-13 10:40 
GeneralRe: My vote of 5 Pin
Marc Clifton24-May-13 11:11
mvaMarc Clifton24-May-13 11:11 
GeneralRe: My vote of 5 Pin
Steve Wellens27-May-13 7:57
Steve Wellens27-May-13 7:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.