Geeks With Blogs
David Redding Blog? What blog? Theres no blog to see here. Please move along

    Welcome back to our newest installment of Tech in 5 minutes.  Today were going to discuss the age old question that every modern family has to confront:

CartoonOne

   Excellent point...however, not today, I meant this one.

CartoonTwo

Special Huggings...yeah in my  world that means:

Kid k = mom + dad;

OR Kid k = (mom + alcohol) + (dad+ alcohol)beer5

    So now I will be your doctor of love and teach you to make kids.  Not only that, but we can illustrate all the major aspects of life via operator overloading,  Like The first job, The first Beer Bong, Getting 80% notes on Guitar Hero 2, How to make Peanut Butter-Saltine-Jalapeno pepper snacks, And of course...Puberty (If that rant doesn't seed the search engines, I don't know what will).  Hell! we can even calculate the chances of toast falling on the carpet butter side down, and give it a score on the triple half gainer it does on the way down.

    Lets get started with the whoopie:

            Man stud = new Man();
            Woman chick = new Woman();
            Alcohol a = new Alcohol();           

 

 

 

            Whoopie whoopie = null;
            while (whoopie == null && !stud.IsPassedOut)
            {
                if (stud.studlyness > chick.standards)
                {
                    whoopie = stud + chick;
                    Kid k = (Kid)whoopie;
                    if (k != null)
                    {
                        stud.studlyness.Huavos = 0;
                    }
                }

 

 

 

                    stud += new Beer();
                    chick += new Daquiri();
            }

 

Pretty accurate eh?  So how does it work? Simple.  Operators are just basically methods with a single character (Read: Lazy Developer) name.  They give us that convenient syntax, but there really is no fundamental difference between

Whoopie whoopie = stud + chick;

And

Whoopie whoopie = stud.Addchick(chick);

Alright, enough alredy, here is how you'd overload that Binary operator:

whoopiegoldburgpublic static Whoopie operator +(Stud s, Chick c)

//since the + operator shouldn't (but does, remember it is basically JUST a static method)
//care about order of values to be operated on go ahead and overload the reverse method signature

public static Whoopie operator +(Chick c, Stud s);

 

    Now, you can stick either of these methods in either the Chick or Stud class, or one in each.  if you try to do both, you'll wind up with an ambiguous reference, since the operator won't know which classes method to call.  This is handy since it's a compiler error instead of catching it at runtime.  I mean, how embarrasing would it be for Your app to say "Cannot add Man and Woman".  It would probably bring up questions about your *ahem* preferences.  And if you worked with the same guys I do, you'd hide under your desk,behind the computer.  On the flipside, you'd learn how to write code without a monitor. But I digress.

     Ok so we can make whoopie, But how do we know to make whoopie? Well simple.  The studs studlyness hast to exceed the woman's *Standards*.  But, since that will most likely NEVER happen off the bat, you have to get some Alcohol involved.  so lets check out the '+='  which actually ends up just being a Binary + operator (Meaning it takes 2 parameters) the '=' part of the operator means we Have to return the same type that were operating on.  so this:

stud += new Beer();

can be read as:

stud is = to stud + a new beer in him();

or

GET THIS MAN A BEER!!!

which ever one gets the point across to you.

we overload this one just like we did with Whoopie:

public static Stud operator +(Stud s, Alcohol a);
{
    s.Studlyness ++; //Same rules as the +=
    return s;
}
public static Stud operator +(Alcohol a, Stud s){return s+a;}

public static Woman operator +(Woman w, Alcohol a)
{
    w.Standards --;
    return w;
}
public static Woman operator +(Alcohol a, Woman w){return w+a;}

In my code, I overloaded these operators in the Alcohol class,  It really doesn't matter where you do it, so long as you do it in one of the classes being operated on.

    So, standards are lowering, "Confidence" is growing, so how do we know when enough is enough? Well, one of two things have to happen, the guy passes out from drinking to much liquid courage, or they finally his Studlyness surpasses her standards and they find a quite spot in the back of someone's car and act like teenage rabbits on spring break.  So, it's easy to check for passed out-y-ness, but what about checking to see if the liquor is working and through a thick set of beer goggles "He could be the one...".  Well, we simply check. overloading the '>' operator is just like overloading the '+' operator, with the caveat that, when you overload an operator like '>' or '<=' you HAVE to have the complementing '<' and '=>'.  this makes sense right?  You cant have a > without a <, that would be fricking crazy!! I mean, it's almost like a 'WT' without the trailing 'F'. The overload looks almost identical to the one for the '+' except you HAVE to return bool (it is a boolean operator afterall).

public static bool operator >(Studlyness studfactor, Standards impossabledream)
{
            //I'm reading on functional programming so i'm TOTALLY in the mood to use
            //these logical operators instead of a standard if/else statement.
            //the & is a logical AND.  Meaning that Both sides of the operator have to
            //evaluate to true. to return true (True,True = true, True,False = False, False,False = false)

            return (studfactor.StudFactor > impossabledream.reqStudFactor) & (studfactor.IncomeFactor > impossabledream.reqIncomeFactor);

}
public static bool operator >(Standards impossabledream, Studlyness studfactor){return studfactor>impossabledream;}

then just do the same for the '<' operator:

public static bool operator <(Studlyness studlyness, Standards standard)
{
            //Same as above, this is the Logical OR operator, this retuns true if either
            //side of the operator is true
            //so True, False = True, True,True = true, False,False = false;
            return (studlyness.StudFactor < standard.reqStudFactor) | (studlyness.IncomeFactor < standard.reqIncomeFactor);
}

public static bool operator >(Standards standards, Studlyness studlyness){return studlyness<standards;}

Ok...so now that our beloved, drunk couple can make Whoopie,  we need to see what the outcome is.  Quite simply, we need to see if the guy is going to loose his Huavos.  So, lets just cast.  Overloading the implicit casting operator is similar to overloading the other operators.  The difference is that this is a Urinary operator (Meaning it only takes one parameter) and either the return type or the parameter have to match the enclosing type (IE if your overloading the casting operator inside the whoopie class either the parameter or the return value have to be of type whoopie).  You also have to state that this is an Implicit operator:

      public class Whoopie
      {
        public static implicit operator Kid(Whoopie e)
        {
            Random TimeForKid = new Random();
            int i = TimeForKid.Next(0, 100);
            if (i >= 50)
                return new Kid();
            else
                return null;
        }

 

 

}

    As you can see, the "Operator" is essentially the return type.  Now, I did something here that you may not want to do without implementing a tryCast() whoopiegoldburgmethod that may return null.  But for the sake so simplicity (read: Lazy Developer) I didn't. 

That's all there is to making whoopie.  I suggest you check out the MSDN Article on operators to see what's available to override and what's not.  If you would like my source code let me know. I have a little console app that I wrote to demonstrate all that stuff up there.  

    So, now that your well equipped for both the developer world, and the real world.  Why not stop by our next AADND meeting at the SRT world headquarters in  Ann Arbor and give me your feedback face to face.  If anything you'll get some valuable FREE training in ASP.Net Caching from the one and only Steven Smith of AspAlliance.com fame and fortune.

    Join me for the next time when we discuss how to make Beer Bongs out of bits of a garden hose and F# or something else equally as interesting.

Posted on Monday, November 5, 2007 12:36 PM Techie .Net Stuff , AADND , Five Min Tech | Back to top


Comments on this post: Tech in 5 minutes: Overloading Operators is Nifty!

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Dave Redding | Powered by: GeeksWithBlogs.net