Click here to Skip to main content
Email Password   helpLost your password?
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:

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralSmall bugs in Extension.zip
amx3000
23:38 7 Nov '07  
        // Number to Hex
public static string ToHex(this System.Byte thisNumber)
{
return String.Format("{0:x2}", thisNumber).ToUpper();
}
public static string ToHex(this System.Int16 thisNumber)
{
return String.Format("{0:x2}", thisNumber).ToUpper();
}
public static string ToHex(this System.Int32 thisNumber)
{
return String.Format("{0:x2}", thisNumber).ToUpper();
}
public static string ToHex(this System.Int64 thisNumber)
{
return String.Format("{0:x2}", thisNumber).ToUpper();
}
public static string ToHex(this System.UInt16 thisNumber)
{
return String.Format("{0:x2}", thisNumber).ToUpper();
}
public static string ToHex(this System.UInt32 thisNumber)
{
return String.Format("{0:x2}", thisNumber).ToUpper();
}
public static string ToHex(this System.UInt64 thisNumber)
{
return String.Format("{0:x2}", thisNumber).ToUpper();
}

I think, string formatters {0:x2} must be {0:x4}, {0:x8} and {0:x16} for Int16, Int32 and Int64 correspondingly. And for unsigned types too.
General.NET 3.0 or C# 3.0?
Mystic Taz
22:53 8 Oct '07  
You mention that this available in .NET 3.0. That is simply .NET 2.0 + WCF/WWF/WPF added. I think you meant .NET 3.5 / C# 3.0. If so, you may want to update the article with this minor fix.

Yeah. I really wish they had named the WPF stuff as .NET 2.5. It would've been less confusing.

BTW. This is VERY cool! Thanks for showing how easy this is. New C# versions always have really cool things that aren't widely talked about. This is one of them.

For example, I've been programming .NET 2.0 for nearly 2 years and I just found out about the ?? operator. (Null-coalescing operator. Look it up!)
GeneraltoUpper
Laurent Muller
20:45 8 Oct '07  
Hello,

If You want to upper case a hex value just use the "X2" instead of "x2" format.
  
public static string toHex(this System.Byte thisNumber)
{
return String.Format("{0:X2}", thisNumber);
}



GeneralRe: toUpper
Matthew Hazlett
21:10 8 Oct '07  
Good to know ty..

Matthew Hazlett
Fighting the good fight for web usability.

GeneralObservation
Matthew Hazlett
9:05 2 Oct '07  
The Visual Studio 'Color.Green' is not true green.  

True Green = RBlush , G:255, BBlush 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!
blackjack2150
1:42 2 Oct '07  
Clean and simple. Very useful article!
GeneralUse ColorTranslator
Uwe Keim
20:19 1 Oct '07  
You could replace your string.Format() stuff with a single call to

http://msdn2.microsoft.com/en-us/library/system.drawing.colortranslator.tohtml.aspx [^]

--
My personal 24/7 webcam
Zeta Producer Desktop CMS Intuitive, completely easy-to-use CMS for Windows.

Zeta Helpdesk Open Source ticket software for Windows and web.

Zeta Uploader Easily send large files by e-mail. Windows and web client.

GeneralRe: Use ColorTranslator
Matthew Hazlett
20:32 1 Oct '07  
This is true but was not the point of the article. The article was about Orcas and adding extensions to existing classes.

Thanks for the tip though.


Matthew Hazlett

Sometimes I miss the simpler DOS days of Borland Turbo Pascal (but not very often).


Last Updated 8 Nov 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010