You probably came across the following declaration in C# and wonder what the hell does keyword this do.
namespace ConsoleApplication1
{
public static class Numbers
{
public static int AddOne(this int a)
{
return a + 1;
}
this keyword in this case makes the method a Extension Method, that means, instead of calling Numbers.AddOne(1) you can use 1.AddOne().
However, there are some restrictions:
1. this keyword must only appear before the first parameter (the modifier of the first parameter)
2. Extension method must be defined in a non-generic static class.
3. Extension method must be static.
The advantage of doing so is that you can see the declaration at the code-auto-completion dropdown list (Intellisense)
A full working example illustrates itself.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public static class Numbers // must be static class
{
public static int AddOne(this int a)
{
return a + 1;
}
// modifier 'this' must be on the first parameter
public static int Add(this int a, int b)
{
return a + b;
}
public static string TestAdd(this string s, string b)
{
return s + b;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(1.AddOne()); // print 2
Console.WriteLine(1.Add(2)); // print 3
Console.WriteLine("1".TestAdd("2")); // print 12
Console.ReadLine();
}
}
}
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Coding Exercise - Restore IP Addresses - C++ - Online Judge
Next Post: How to Implement Integer Square Root in C/C++?