Friday, April 4, 2008

Enhancing C#'s switch statement with a fluent API

A colleague pointed me to this article today.  It shows a very clever set of utility classes that can dramatically improve the usefulness of the "switch..case" concept.  Since the C# language can't be extended, it is implemented as a fluent API that tries to mimic the built-in switch statement.

The most interesting use to me is the generics-based double dispatch using delegates that enables a sort of visitor pattern:

void Do(Control c) 
{
new Switch(c)
.Case<Label>(l =>
{
// ...
})
.Case<Button>(b =>
{
// ...
})
.Default(cc =>
{
// ...
});
}



An interesting oddity of the implementation is that the various Case() overloads are implemented as Extension methods on the Switch types. That is the only thing I don't like in the linked article. It exploits a "feature" of Extension methods that sorta allows you to call methods on null references. The case "statements" (method calls) are short-circuited by returning null and additional calls to Case() check for the null "this" pointer (the fake "this" which is the first parameter to extension methods) and exits quickly. To me, this seems like abuse of extension methods since the same thing can easily be accomplished with a traditional class.



Here is a modified version of the Switch<T> class implemented as a simple class without the extension methods:




public class Switch<T>
{
public T Object { get; private set; }
private bool hasBroken = false;

public Switch(T obj)
{
this.Object = obj;
}

public Switch<T> Case(T other, Action<T> action)
{
return this.Case(other, action, SwitchBehavior.Break);
}

public Switch<T> Case(T other, Action<T> action, SwitchBehavior behavior)
{
return this.Case(x => object.Equals(x, other), action, behavior);
}

public Switch<T> Case(Func<T, bool> condition, Action<T> action)
{
return this.Case(condition, action, SwitchBehavior.Break);
}

public Switch<T> Case(Func<T, bool> condition, Action<T> action, SwitchBehavior behavior)
{
if (!this.hasBroken && condition(this.Object))
{
action(this.Object);
if (behavior == SwitchBehavior.Break)
this.hasBroken = true;
}

return this;
}

public void Default(Action<T> action)
{
this.Case(t => true, action, SwitchBehavior.Break);
}
}

public enum SwitchBehavior { FallThrough, Break }



A functional C# (type)switch - B# .NET Blog

29 comments:

Anonymous said...

[B]NZBsRus.com[/B]
Lose Slow Downloads Using NZB Downloads You Can Swiftly Search HD Movies, Games, MP3s, Applications and Download Them at Fast Rates

[URL=http://www.nzbsrus.com][B]NZB[/B][/URL]

Anonymous said...

Predilection casinos? abolished onto this environmental [url=http://www.realcazinoz.com]casino[/url] waterway effluxion and wing it calumny online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also deter our up to the translate [url=http://freecasinogames2010.webs.com]casino[/url] pointer at http://freecasinogames2010.webs.com and snowball the outstanding chief genially touched in the prime gifted !
another adscititious [url=http://www.ttittancasino.com]casino spiele[/url] locality is www.ttittancasino.com , because german gamblers, blurt outdoors in unrestrained online casino bonus.

Anonymous said...

Amiable brief and this post helped me alot in my college assignement. Say thank you you as your information.

Anonymous said...

Someone deleted a variety of links from load2all and mediafire servers.

From now, we will use www.tinyurlalternative.com as our main [url=http://www.tinyurlalternative.com]url shortener[/url], so every link will be there and visible for everyone.

You can choose from several great [url=http://kfc.ms]short url[/url] names like:

kfc.ms easysharelink.info jumpme.info megauploadlink.info megavideolink.info mygamelink.info myrapidsharelink.info mytorrentlink.info myurlshortener.com mywarezlink.info urlredirect.info urlshrinker.info weblinkshortener.com youtubelink.info and many others.

They include over 60 different available domains and the [url=http://myurlshortener.com]url shortener[/url] service work properly for free without any registration needed.

So we think it is good notion and suggest you to use [url=http://urlredirect.info]url redirect[/url] service too!

Thank you.

Anonymous said...

excellent points and the details are more specific than elsewhere, thanks.

- Murk

Anonymous said...

ha, I am going to experiment my thought, your post get me some good ideas, it's really amazing, thanks.

- Thomas

Anonymous said...

post51, http://www.rc.umd.edu/cstahmer/cogsci/ viagra pro, dmbe4, http://www.rc.umd.edu/ order viagra

buy generic viagra said...

I liked this blog, i think is very interesting, most of all for the new ideas that this blog talk.

pay per head said...

Thanks for sharing such an interesting post with us. You have made some valuable points which are very useful for all readers

London Crumpet said...

London escorts directory London Crumpet is created to expose Independent escorts and escort agencies in London. Everybody can post their advert on this directory for FREE.

pay per head said...

Thanks for your suggestion. I really appreciate that you took all this time to try and help us. Keep up the good work. Keep on taking action.

Anonymous said...

Topamax without prescription It is currently under clinical trials to determine if it is useful in treating posttraumatic stress disorder. http://www.jordanbrewers.com/ - topamax sale Topamax is an anticonvulsant drug that treats many different conditions in children and adults such as epilepsy. Topamax is an anticonvulsant drug that treats many different conditions in children and adults such as epilepsy.

Anonymous said...

workplace dating investigations http://loveepicentre.com/success_stories.php best black online dating

Anonymous said...

the dating diaries by kristen kemp http://loveepicentre.com/ dating at middle age

Anonymous said...

[url=http://loveepicentre.com/][img]http://loveepicentre.com/uploades/photos/1.jpg[/img][/url]
fun free dating ideas [url=http://loveepicentre.com/success_stories.php]apolo ohno dating shawn johnson[/url] yahoo dating group norfolk uk
difference between dating and relationship [url=http://loveepicentre.com/]marisol nichols resurrection blvd dating[/url] marcus allen dating hollywood
newest online dating websites [url=http://loveepicentre.com/]free phone dating line service[/url] wholesome online dating

Anonymous said...

[url=http://loveepicentre.com/][img]http://loveepicentre.com/uploades/photos/5.jpg[/img][/url]
dating banker5870 [url=http://loveepicentre.com/map.php]dating naked woman[/url] 5 star introductions ukraine dating agency
contemporary dating and its harm [url=http://loveepicentre.com/]gemini cancer cusp woman dating[/url] chatfields dating service
married women dating lesbians [url=http://loveepicentre.com]dating hangouts in tucson[/url] professional middle age dating websites

Anonymous said...

[url=http://loveepicentre.com/faq.php][img]http://loveepicentre.com/uploades/photos/4.jpg[/img][/url]
free adult dating australia [url=http://loveepicentre.com/advice.php]kansas male dating[/url] is jolene van vugt dating travis
dating man [url=http://loveepicentre.com]filanderer dating sites[/url] dating services for no sex marriage
free senior christian dating [url=http://loveepicentre.com/map.php]gay dating website[/url] accuracy of carbon dating

Anonymous said...

psp ebook reader pixie http://audiobookscollection.co.uk/de/HTML-XHTML-and-CSS-All-in-One-Desk-Reference-For-Dummies/p218080/ free ebook pdf pavel [url=http://audiobookscollection.co.uk/Taylor-Andrew-Wilson/m123219/]ebook reader software for linux computers[/url] watership down ebook torrent

Anonymous said...

customize sneakers ebook http://audiobookscollection.co.uk/fr/Becoming-A-Translator-An-Accelerated-Course/p218015/ mosaic art ebook download [url=http://audiobookscollection.co.uk/es/Biolog-a-Molecular/c2953/?page=2]gerald corey groups ebook[/url] basic electrical technology ebook

Anonymous said...

balagurusamy free ebook of c http://audiobooksplanet.co.uk/de/V-B-Ho/m128116/ ebook for ds [url=http://audiobooksplanet.co.uk/Summer-of-My-First-Love/p206450/]ebook romeo and juliet[/url] michael webb ebook free

Anonymous said...

larion senators ebook http://audiobooksworld.co.uk/de/Rodney-Crowell/p29119/ free ebook structured query language [url=http://audiobooksworld.co.uk/it/V-S-L-Vov/m128038/]gambling ebook[/url] ascension ebook

Anonymous said...

slide organization software http://buyoem.co.uk/product-19738/KakaSoft-Folder-Protector-5-3 blackberyy 8703e software [url=http://buyoem.co.uk/product-23928/ArzooSoft-USB-Threat-Defender-1-0]adobe photoshop academic software[/url] boston software office
[url=http://buyoem.co.uk/product-37225/Notepad-Pro-3-2]Notepad Pro 3.2 - Software Store[/url] sun managment software linux download
[url=http://buyoem.co.uk/product-25350/Microsoft-BizTalk-Server-2009-Branch-Edition-x86][img]http://buyoem.co.uk/image/2.gif[/img][/url]

Anonymous said...

are blog posts reason enough to get a company to sue a person according to the Indian law?


My homepage ... transvaginal mesh lawsuit

Anonymous said...

What i do not realize is actually how you're not actually much more neatly-appreciated than you may be now. You're very
intelligent. You understand thus significantly on the subject
of this matter, produced me in my view consider it
from so many various angles. Its like women and men are not interested unless it is one thing to accomplish with Lady gaga!
Your individual stuffs great. All the time deal with it up!


Here is my blog post: www.lawforparents.com

Anonymous said...

If some one wants to be updated with most up-to-date technologies then he must be pay a visit this website and be
up to date daily.

Also visit my blog ... dental implants cost

Anonymous said...

I like the helpful info you provide in your articles. I will
bookmark your blog and check again here regularly. I am quite certain I will
learn plenty of new stuff right here! Best of
luck for the next!

Also visit my web site: http://Affordable-Dental-Plan.org/

Anonymous said...

jason kitley boise idaho dating http://loveepicentre.com/map/ 100 free sexy dating site
phone chat dating singles [url=http://loveepicentre.com]free latina dating[/url] christian senior personal dating sites
latin dating service [url=http://loveepicentre.com/faq/]best rated online free dating site[/url] dating naples fl [url=http://loveepicentre.com/user/markspeed/]markspeed[/url] christian dating dating married service woman

Unknown said...

Nice post very helpful

dbakings

Anonymous said...

electronic cigarette, smokeless cigarettes, e cigarette, ecigarette, e cigarette health, e cigarette