Click here to Skip to main content
Licence CPOL
First Posted 1 Oct 2007
Views 16,070
Downloads 174
Bookmarked 18 times

Creating a Basic Extension Method

By Matthew Hazlett | 7 Nov 2007
Extending System.Color with .toHTML()

1

2
1 vote, 12.5%
3
6 votes, 75.0%
4
1 vote, 12.5%
5
4.00/5 - 8 votes
μ 4.00, σa 1.10 [?]
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

Web Developer

United States United States

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.
 



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralSmall bugs in Extension.zip Pinmemberamx300023:38 7 Nov '07  
Question.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    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120210.1 | Last Updated 8 Nov 2007
Article Copyright 2007 by Matthew Hazlett
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid