C# 3.0 Extension Methods As Adapters

[digg]

Extension methods provide public / internal extensions to the already existing types. And the design pattern that provides this functionality is the visitor pattern, but the draw back of the visitor is you have to have all the hooks planted in the class hierarchy  according to the pattern to make it workable. But the extension methods provide you this pattern right out of the box. I’ll go into more details of the visitor pattern some later time, I have plans to discuss the design patterns in details.

I’ll show you how we can use the extension methods to work like adapters. Adapter design pattern, also known as a wrapper pattern, is used to take care of incompatibilities between objects, more on it in some later session. If you ever developed a java application, the objects in java have inbuilt  capability of thread synchronization like waiting on an object to be signaled using the methods like notify, wait etc. I was thinking to get the same  functionality using C#. C# provides the functionality through System.Threading.Monitor class that allows synchronization between threads within the same process. Here is how we can achieve this java functionality in C#.

using System.Threading;

namespace System
{
    public static class ObjectExtension
    {
        public static void Enter(this object obj)
        {
            Monitor.Enter(obj);
        }

        public static void Exit(this object obj)
        {
            Monitor.Exit(obj);
        }

        public static void Notify(this object obj)
        {
            Monitor.Pulse(obj);
        }

        public static void NotifyAll(this object obj)
        {
            Monitor.PulseAll(obj);
        }

        public static bool Wait(this object obj)
        {
            return Monitor.Wait(obj);
        }

        public static bool Wait(this object obj, int millisecondsTimeout)
        {
            return Monitor.Wait(obj, millisecondsTimeout);
        }
    }
}

Here is an example class for its minimal usage –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Shams
{
    [Serializable]
    public class Example
    {
        private static Object SyncObject = new Object();

        // Constructors
        public Example() { }

        public bool Block()
        {
            lock (SyncObject)
            {
                bool status = true;

                try
                {
                    status = SyncObject.Wait();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.ToString());
                    status = false;
                }
                return status;
            }
        }

        public void Release()
        {
            lock (SyncObject)
            {
                SyncObject.Notify();
            }
        }

        public void ReleaseAll()
        {
            lock (SyncObject)
            {
                SyncObject.NotifyAll();
            }
        }
    }
}

And here is our test app with entry point, Main…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Shams
{
    class Program
    {
        static void Main(string[] args)
        {
            // creat the example object
            Example example = new Example();
            Debug.WriteLine("Main thread..." + 
                Thread.CurrentThread.GetHashCode().ToString());
            new Thread(delegate()
            {
                //// block for ever...
                Debug.WriteLine("Entering thread..." + 
                    Thread.CurrentThread.GetHashCode().ToString());
                
                example.Block();
                
                Debug.WriteLine("Leaving thread..." + 
                    Thread.CurrentThread.GetHashCode().ToString());
            }).Start();

            // lets sleep for 5 secs, tired need rest..
            System.Threading.Thread.Sleep(5000);
            example.Release();
            
            System.Threading.Thread.Sleep(1000);
            Debug.WriteLine("Main thread again..." + 
                Thread.CurrentThread.GetHashCode().ToString());
            
            /*  The output is :-
             *  Main thread...9
             *  Entering thread...10
             *  Leaving thread...10
             *  The thread 0x16c4 has exited with code 0 (0x0).
             *  Main thread again...9
            */  
        }
    }
}

See how nicely we got the Adapter’s functionality using C# 3.0’s Extension mechanism that is we have extended the Objects functionality with the wrappers around the Monitors and that actually mimics the Adapters (The Adapter Design Pattern). I’ll give you more examples on it later, when i cover threading and LINQ topics. Looking forward to your comments and have a good one :)

If you enjoyed reading this blog, leave your valuable feedback and consider subscribing to the RSS feed. You can also subscribe to it by email. Also, you can follow me on Twitter. Thank you!

 

Technorati Tags: ,

Comments (5) -

clicking Here
12/8/2017 4:56:23 AM #

What's up, after reading this awesome post i am also cheerful to share my familiarity here with friends.

free robux codes 2017 november
12/9/2017 11:55:30 AM #

Hi i subbed and liked and turned notifications on my friend Jeshua Abraham sent me my username is Imahackjailbreak and his is ThinkTail Smile

quick cash loans
12/10/2017 6:40:23 AM #

fast payday loans  payday loan online - http://getloansusapersonal.com/  online loan  cash loans no credit check - https://loanswayer.com/

gooker toadstools
12/10/2017 8:20:22 AM #

I love your site.. continue the good work! Have you any idea the actual theme is incidentally?  Also visit my homepage ...  gooker toadstools - http://gookertoadstools.blogspot.com

no credit check payday loans
12/10/2017 11:13:34 PM #

no credit check loans  cash advance loans - http://getloanstodayonline.com/  online payday loans no credit check  payday loans bad credit - https://loanswayer.com/

free live me coins
12/11/2017 3:31:45 AM #

I couldn't refrain from commenting. Perfectly written!

payday loans no credit
12/11/2017 5:14:26 AM #

online payday loans no credit check  payday loans for bad credit - http://paydaymnku.com/  loans for bad credit  no credit check loans - http://paydaymnku.com/  cash loans no credit check

Wanda
12/11/2017 3:51:07 PM #

I really like your site, continue the great work! Do you know which theme this is by the way? Also, I shared this on Twitter.  Thanks!  my blog ...  Wanda - http://bfb7904p.bget.ru/profile/danniemcdow

Dorothy
12/11/2017 3:55:31 PM #

Hi, all the time i used to check blog posts here early in the daylight, as i love to gain knowledge of more and more.

Augustina
12/11/2017 5:49:40 PM #

I really like your website, continue the good work! Do you have any idea what your theme is by the way?   Thank you  Check out my blog:  Augustina - www.fanmail.biz/.../viewtopic.php

làm bằng đại học tphcm
12/11/2017 10:26:18 PM #

I am in fact thankful to the holder of this web page who has shared this great article at at this place.

casino games free
12/11/2017 11:46:40 PM #

free casino slot games  best online casinos - http://casino17rich7online.com/  casino slot machines  casino games for free - http://richcasino2online.com/

payday loans for bad credit
12/12/2017 3:47:58 PM #

payday loans no credit check  payday loans no credit - https://smajloans.com/  payday loans no credit  no credit check loans - https://smajloans.com/  online payday loans no credit check

casino online
12/13/2017 10:50:28 AM #

online casino no deposit  online casino - http://slotsmegacasino.com/  best online casino  online casino usa - http://playslotscasino888.com/

Electronicrepairegypt.Com
12/14/2017 8:27:47 PM #

I do not even know how I stopped up right here, however I thought this submit was once great. I don't recognise who you might be but definitely you are going to a well-known blogger for those who aren't already. Cheers!

Skye
12/15/2017 12:19:56 AM #

I really like your site.. continue the great work. Do you have any idea what theme this is by the way?   Thank you!  Here is my web page -  Skye - www.humour-france.com/modules.php

casino online
12/15/2017 3:14:50 AM #

casino games free  casino free games - http://real777money.com/  slot machines  casino games free - http://real777money.com/  casino slots

Logan
12/16/2017 2:10:30 AM #

naturally like your web site however you need to check the spelling on several of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to tell the reality however I will surely come again again.

http://farsicad.com
12/16/2017 7:10:56 PM #

Até este lugar você encontra os melhores!

Life Experience Degree
12/17/2017 11:57:28 AM #

One of our visitors recently proposed the following website.

internal bleeding xarelto
12/17/2017 5:02:02 PM #

Hello Dear, are you actually visiting this web page on a regular basis, if so afterward you will without doubt obtain good knowledge.  Review my site  internal bleeding xarelto - xareltoattorneys.bitbucket.org/.../index.html

Mylab Box Review
12/17/2017 6:44:29 PM #

It doesn't get any easier than MyLab Box.

casino online usa
12/20/2017 6:08:20 AM #

online casino games  casino games - http://casinoline17.com/  online casino  casino online - http://casinoline17.com/  online casino real money

online loans
12/22/2017 6:53:29 PM #

apply for payday loans  loans online application - http://loansmart24.com/  no credit check payday loans instant approval  payday loans online legit - http://loansmart24.com/

Laurinda
12/23/2017 3:40:27 PM #

Good web site you have here.. It's hard to find high-quality writing like yours these days. I really appreciate people like you! Take care!!  my web site  Laurinda - boletinmexico.com.mx/.../

best bug out backpack
12/28/2017 1:45:58 AM #

May I simply just say what a relief to uncover someone who truly knows what they are talking about online. You actually understand how to bring a problem to light and make it important. A lot more people ought to look at this and understand this side of the story. I can't believe you aren't more popular given that you certainly have the gift.

I have fun with, cause I discovered exactly what I was having a look for. You've ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye  Feel free to visit my web page ...  Soñar Con Un Accidente De Coche California - abogadotraficoca.netlify.com/.../...-CA-95923.html

composiçăo do pro burn x
12/29/2017 8:09:37 PM #

Você é possível que adquirir direta do sítio oficial do resultado com descontos imperdíveis para esta semana.

free casino games
12/29/2017 11:26:38 PM #

casino online  casino games - http://bom777casino.com/  real money casino  free casino games - http://bom777casino.com/  free casino games

sardinha evolution ebook
12/30/2017 8:32:11 AM #

Leve ao lume e deixe ferver algo.

onde comprar super chá da vida
12/30/2017 9:18:57 AM #

É praticamente um aprendizado milenar.

payday loans
1/3/2018 10:05:18 PM #

loans no credit  loans for bad credit - http://loansdranz.com/  loans no credit check  loans for bad credit - http://loansdranz.com/  payday loans online no credit check

mobile car detailing near me
1/11/2018 5:58:25 AM #

When someone writes an piece of writing he/she maintains the plan of a user in his/her brain that how a user can know it. Thus that's why this piece of writing is outstdanding. Thanks!

viagra
1/13/2018 11:43:38 AM #

This is the perfect blog for everyone who wants to find out about this topic. You realize a whole lot its almost tough to argue with you (not that I personally would want to…HaHa). You certainly put a brand new spin on a topic that's been written about for decades. Excellent stuff, just wonderful!

online casinos real money
1/18/2018 12:27:33 PM #

list of all harrah's casinos  game slots - http://bablcasinogames.com/  triple diamond slots 5x  triple diamond slots 5x - http://bablcasinogames.com/  best free online casino

vk-hacker.ru
1/26/2018 7:02:23 PM #

Cada cântaro possuem 30 cápsulas.                   Efetivamente!     Nunca!

car insurance quotes online
1/26/2018 7:49:08 PM #

cheap car insurance companies  car insurance companies - http://auto24insurance24online.com/  auto insurance program  cheap car insurance calculator - https://advanceinsur.com/

online casinos 2016
1/30/2018 6:44:49 AM #

vegas casino games  pogo casino slots - http://casinousaonlinelist.com/  vegas casino games  casino games real money - http://casinousaonlinelist.com/

online casino gambling
2/11/2018 9:30:58 PM #

casino casino  slot online - http://bom777casino.com/  casino games  pogo casino slots - http://casinoline17.com/  aol games free casino

auto insurance quotes online
2/14/2018 8:36:25 PM #

auto insurance companies  cheap car insurance online - https://advanceinsur.com/  car insurance policy  car insurance companies - http://auto100insurance24quotes.org/

weight loss drugs prescription
2/14/2018 11:11:04 PM #

best diet pill available  prescription weight loss pills - http://regimenforfeit.com/  diet pill  appetite suppressant - http://regimenforfeit.com/  best diet pills that work

car insurance comparison
2/14/2018 11:40:26 PM #

cheap auto insurance  cheap car insurance quotes comparison - https://advanceinsur.com/  car insurance  car insurance - http://auto24insurance24online.com/

Add comment