Click here to Skip to main content
6,306,412 members and growing! (16,653 online)
Email Password   helpLost your password?
Languages » C# » General     Beginner License: The Code Project Open License (CPOL)

Creating a Basic Extension Method

By Matthew Hazlett

Extending System.Color with .toHTML()
C# 3.0, Windows, .NET 3.0VS2008, Dev
Posted:1 Oct 2007
Updated:7 Nov 2007
Views:9,827
Bookmarked:13 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
8 votes for this article.
Popularity: 3.61 Rating: 4.00 out of 5

1

2
1 vote, 12.5%
3
6 votes, 75.0%
4
1 vote, 12.5%
5
Screenshot - HTMLExt.gif

Background

One thing many developers wrestle with is classes that don't have the features they want/need. How many times have you been working on a project and wished there was a .toHex() function built right into the Integer type?

A few developers have created wrapper classes, these allow you to add virtual functions to existing objects and extend let's say System.String with a new virtual method called .toPiglatin().

With .NET 3, you no longer need to use those extension methods, it's built right into the language. I am going to show you how to create a simple extension that's part of the color type and is called .toHTML().

Building the Extension Class

This could not possibly get any easier.

using System;

namespace HTMLExt
{
    public static class MyExtensions
    {
        public static string toHex(this System.Byte thisNumber)
        {
            return String.Format("{0:x2}", thisNumber).ToUpper();
        }

        public static string toHTML(this System.Drawing.Color thisColor)
        {
            return String.Format("#{0}{1}{2}", thisColor.R.toHex(), 
			thisColor.G.toHex(), thisColor.B.toHex());
        }
    }
}

This is the heart of the entire program, this is where you define methods that will extend existing objects. First you will need to name your namespace and make the MyExtensions static class.

The first is a simple .toHex() extension that will extend System.Byte so you can use statements like this:

string HexValue = Color.Red.R.toHex();

This will yield the expected result of FF.

The second extension is called .toHTML() and it extends System.Drawing.Color.
What this extension does is it formats all the .toHex() results as a valid HTML color and returns it so you can do stuff like this:

string HTMLColor = Color.Blue.toHTML(); 

This will yield the expected result of #0000FF.

Sample Application

What the sample application does is it takes the color you selected with the standard colorDialog and returns its HTML value. Here is the function that does it all:

private void button1_Click(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
        HtmlColor.Text = colorDialog1.Color.toHTML();
}

Pretty self explanatory, it displays a color dialog, then converts the selected color to HTML. Well, that's it for this brief article, I hope you have fun with this new technique. I know I have several uses in mind already.

Extensions.zip

These are some other extensions I wrote to start my core library of extensions:

  • Byte.ToHex()

    Converts bytes to their hex value. (Also for Int16, 32, 64 and UInt16, 32, 64)

  • Color.ToHTML()

    Converts a color to its HTML color string

  • Char.ToUpper()

    Converts a Char to upper case

  • Char.ToLower()

    Converts a char to lower case

  • String.isNumber()

    Is the given string a number?

  • String.isEmail()

    Is the given string an email address?

  • String.IsURL()

    Is the given string a valid URL (format: http://devclarity.com)

  • String.ContainsPunctuation()

    Are there any punctuation marks in the given string

  • String.ToTitle()

    Converts the string to title case (every word's first char is uppercase)

  • String.ToProper()

    Converts the string to proper case (the first letter is uppercase)

  • String.ToPigLatin() [totally useless]

    Converts a string to piglatin

  • ICollection<string>.Join(", ")

    Joins an array or a collection of strings separated by commas

  • ICollection<int>.Join(", ")

    Joins an array or a collection of integers separated by commas

License

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

About the Author

Matthew Hazlett


Member
I started programming for fun when I was about 10 on an Franklin Ace 1000.

I still do it just for fun but it has gotten me a few jobs over the years. More then I can say for my Microsoft Certifications. Smile

The way I learned was by example, now its time to give back to the next generation of coders.



Occupation: Web Developer
Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
GeneralSmall bugs in Extension.zip Pinmemberamx300023:38 7 Nov '07  
General.NET 3.0 or C# 3.0? PinmemberMystic Taz22:53 8 Oct '07  
GeneraltoUpper PinmemberLaurent Muller20:45 8 Oct '07  
GeneralRe: toUpper PinmemberMatthew Hazlett21:10 8 Oct '07  
GeneralObservation PinmemberMatthew Hazlett9:05 2 Oct '07  
GeneralNicely done! Pinmemberblackjack21501:42 2 Oct '07  
GeneralUse ColorTranslator PinsitebuilderUwe Keim20:19 1 Oct '07  
GeneralRe: Use ColorTranslator PinmemberMatthew Hazlett20:32 1 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 7 Nov 2007
Editor: Deeksha Shenoy
Copyright 2007 by Matthew Hazlett
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project