Page 1 of 1

Extension Methods in C#

#1 LarcaCode  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 16
  • View blog
  • Posts: 21
  • Joined: 30-July 12

Posted 13 February 2013 - 04:21 AM

*
POPULAR

Welcome to my first tutorial about extension methods in C#.

At first, lets have a quick overview of this tutorial:

  • Introduction
  • What are extension methods?
  • Creating Extenstion Methods
  • Using Extenstion Methods
  • Known problems

Lets get started!


1) Introduction

Let's assume you want to convert an integer value to a hex value and print it out. Your code may look like this:
//...
int i = 15;
string hex = String.Format("0x{0:X}", i);	// get hex value and convert to string
Console.WriteLine(i.ToString());	// output: 15
Console.WriteLine(hex);	// output: 0xF
//...


Looks already quite simple, doesn't it? But...
In line 3 of this little code snippet the integer i is converted to a string by using .ToString(). Wouldn't it be nice if we could just write
//...
Console.Writeline(i.ToHex());
//...


As we cannot change or add a new method to the Integer Class, one pretty nice and clean solution is the use of extension methods.
(.ToString() is in fact not an extension method. )


2) What are extension methods?

Extension methods are external methods which feel like they are part of a specific class (in our example: the Integer Class).
They are actually "just" syntactical sugar for a better/easier code handling and to make your code look cleaner.


3) Creating extension methods

Firstly, create a new class File. I usually call it something like "IntegerExtensions" or just "Extensions".
The keyword static in the class signature is required as extension methods have to be in static classes as static methods. And it must be public.
Your code should now look like this:
using System;
using System.Collections.Generic;
using System.Text;

namespace ExtensionMethod
{
    public static class IntegerExtensions
    {
		
    }
}



Now let's define the signature of the extension method we want:
public static string ToHex(this int i)
{

}


The method is pulbic and static. And it's return type is defined as a string (to use it in Console.Writeline()).
The first parameter must be the type of object that we are creating this extension method for - marked with this.
After this there can follow as much parameters of any type as needed.

The complete implementation should look like this:
using System;
using System.Collections.Generic;
using System.Text;

namespace ExtensionMethod
{
    public static class IntegerExtensions
    {
		public static string ToHex(this int i)
		{
			return String.Format("0x{0:X}", i);
		}
    }
}



That's it! Now we can use our new int extension.


4) Using extension methods

Well, to convert an integer value to a hex value is now very, very simple:
//...
int i = 15;
Console.Writeline(i.ToString());
Console.Writeline(i.ToHex());
//...




5) Known problems

You may get the following.NET version error:
Posted Image
There is a simple solution for this problem. Insert the following code in the Extension.cs outside your namespace:
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
    public sealed class ExtensionAttribute : Attribute { }
}


Here is a nice article about "Using Extension Methods in .net 2.0"



Thats the end of this tutorial.
It should gave you a quick overview of the opportunities of Extension Methods in C# - creation and useage.


This post has been edited by LarcaCode: 13 February 2013 - 01:48 PM


Is This A Good Question/Topic? 6
  • +

Replies To: Extension Methods in C#

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,653
  • Joined: 02-June 10

Posted 13 February 2013 - 11:55 AM

Nice work!

This post has been edited by tlhIn`toq: 13 February 2013 - 12:06 PM

Was This Post Helpful? 0
  • +
  • -

#3 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,653
  • Joined: 02-June 10

Posted 15 February 2013 - 01:58 PM

Don't mean to hijack your tutorial.
I just wanted to share another real-world example for your readers.

We all do logs of what's going on in our applications (or we should).
I for one can never remember the right format codes for DateTime.ToString to give me the 24hour or military style of writing dates and time. For example 14Feb13 1550hrs

So an extension method for DateTime can give you DateTime.ToMilSpecTime

Then anywhere you write a log or display some info on your application it can follow this exact format.

Posted Image

Here's the Datetime region of my Extension methods file.
Notice you can even overload extension methods for things like "ShowSeconds" in this case.
    #region DateTime

    /// <summary>24hrs time, also known as US Military format.  143010hrs</summary>
    public static string ToMilSpecTime(this DateTime Datetime, bool ShowSeconds, bool ShowHrsSuffix)
    {
        string formatter = "HHmm" + (ShowSeconds ? "ss" : string.Empty);
        return Datetime.ToString(formatter) + (ShowHrsSuffix ? "hrs" : string.Empty);
    }

    /// <summary>By default without specifying seconds and "hrs" suffix are turned on </summary>
    public static string ToMilSpecTime(this DateTime Datetime)
    {
        return ToMilSpecTime(Datetime,true, true);
    }

    public static string ToMilSpecDate(this DateTime Datetime)
    {
        return Datetime.ToString("ddMMMyy");
    }

    #endregion DateTime



Posted Image

This post has been edited by tlhIn`toq: 15 February 2013 - 02:00 PM

Was This Post Helpful? 3
  • +
  • -

#4 LarcaCode  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 16
  • View blog
  • Posts: 21
  • Joined: 30-July 12

Posted 18 February 2013 - 07:24 AM

It's appreciated :)
A really nice real-world example.
Was This Post Helpful? 0
  • +
  • -

#5 CodMnk2b  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 14
  • Joined: 07-February 13

Posted 08 April 2013 - 09:04 AM

Thanks for the tutorial.

Found 2 typos, well, a typo and a syntax error.:

in 3) first paragraph says pulbic instead of public

in 4) in the code snippet, says Console.Writeline, instead of WriteLine
Was This Post Helpful? 0
  • +
  • -

#6 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 115
  • View blog
  • Posts: 1,355
  • Joined: 14-January 10

Posted 22 April 2013 - 07:21 PM

Just a note for future readers that this is only works for .NET Framework 3.5 or later. Was working on a project not long ago targeting .NET Framework 3.0 and I was unable to use extension methods.
Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,653
  • Joined: 02-June 10

Posted 22 April 2013 - 09:04 PM

That's not true. You can use extension methods as far back as C# 3.0, Framework 2.0 and VS 2008.
It was covered here fairly well.
http://stackoverflow...h-2-0-framework

Then repeated and expanded on here
http://www.codethink...thods-in-net-20
Was This Post Helpful? 0
  • +
  • -

#8 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 944
  • View blog
  • Posts: 2,353
  • Joined: 15-February 11

Posted 29 September 2013 - 06:47 PM

Very good tutorial. This beats calling a static method 20 times. Clean and simple.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1