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

Creating a Basic Extension Method

Rate me:
Please Sign up or sign in to vote.
4.00/5 (8 votes)
7 Nov 2007CPOL2 min read 36.7K   339   18   8
Extending System.Color with .toHTML()
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.

C#
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:

C#
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:

C#
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:

C#
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:

  • C#
    Byte.ToHex()

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

  • C#
    Color.ToHTML()

    Converts a color to its HTML color string

  • C#
    Char.ToUpper()

    Converts a Char to upper case

  • C#
    Char.ToLower()

    Converts a char to lower case

  • C#
    String.isNumber()

    Is the given string a number?

  • C#
    String.isEmail()

    Is the given string an email address?

  • C#
    String.IsURL()

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

  • C#
    String.ContainsPunctuation()

    Are there any punctuation marks in the given string

  • C#
    String.ToTitle()

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

  • C#
    String.ToProper()

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

  • C#
    String.ToPigLatin() [totally useless]

    Converts a string to piglatin

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

    Joins an array or a collection of strings separated by commas

  • C#
    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)


Written By
Web Developer
United States United States
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.



Comments and Discussions

 
GeneralSmall bugs in Extension.zip Pin
amx30007-Nov-07 22:38
amx30007-Nov-07 22:38 
Question.NET 3.0 or C# 3.0? Pin
Mystic Taz8-Oct-07 21:53
Mystic Taz8-Oct-07 21:53 
GeneraltoUpper Pin
Laurent Muller8-Oct-07 19:45
professionalLaurent Muller8-Oct-07 19:45 
GeneralRe: toUpper Pin
Matthew Hazlett8-Oct-07 20:10
Matthew Hazlett8-Oct-07 20:10 
GeneralObservation Pin
Matthew Hazlett2-Oct-07 8:05
Matthew Hazlett2-Oct-07 8:05 
The Visual Studio 'Color.Green' is not true green.

True Green = RBlush | :O , G:255, BBlush | :O or #00FF00
'Color.Green' is #008000 and that is very strange! (Is ms color blind?)

Color TrueGreen = Color.FromArgb(0, 255, 0);
TrueGreen.ToHTML(); // This = #00FF00 Smile | :)

Matthew Hazlett
Sometimes I miss the simpler DOS days of Borland Turbo Pascal (but not very often).
GeneralNicely done! Pin
blackjack21502-Oct-07 0:42
blackjack21502-Oct-07 0:42 
GeneralUse ColorTranslator Pin
Uwe Keim1-Oct-07 19:19
sitebuilderUwe Keim1-Oct-07 19:19 
GeneralRe: Use ColorTranslator Pin
Matthew Hazlett1-Oct-07 19:32
Matthew Hazlett1-Oct-07 19:32 

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.