Introduction
Have you ever needed a method and you didn't find in the class? Have you dreamed that you can add this functionality to the built-in class? This is now available through .Net Framework 3.5. You can extend any class you want by adding the function you want directly without the need of inheritance.
Using the code
To demonstrate how to make this. I want to add a method that give me how many times a string is a repeated in string e.g. 'o' is repeated 2 times in "How are you?"
Let's Start.
Create a new Project any type you like "Windows Application", "WPF", "Console Application" or "Web Application". I'll choose a Windows Desktop Application.
Part 1: Creating the extending method.
After the project is created, add new class and name it "Occur.cs"
After the class is created, Make the class as a static class by adding static in front of class reserved word
You will have something as this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtentionMethodsDemo
{
static class Occur
{
}
}
Now, we will add the function will perform the repetition. I'll depend on the built-in IndexOf method to detect how many times the string is repeated
public static int OccuranceOf (this string word, string SearchText)
{
int occur = 0;
int i = -1;
i = word.IndexOf(SearchText);
while (i >= 0)
{
occur++;
i = word.IndexOf(SearchText, i + 1);
}
return occur;
Notes:
1. The method is static.
2. Check the first parameter to the function which is 'this' which reflects that this method is extension to the to next variable.
Now Build the solution.
Part 2: Testing the function
Now Test if it will work.
Add 2 TextBox and a Button to Form to get something like this
The user will enter the text which he wants to search in in the first textbox, and the search word in the 2nd textbox.
Now coding the button1
check this I found the method OccuranceOf in the text property (which is a string) of the textbox
The complete code of the button is as following
private void button1_Click (object sender, EventArgs e)
{
int x = textBox1.Text.OccuranceOf(textBox2.Text);
MessageBox.Show("'" + textBox2.Text + "' occured " + x.ToString() + " times in the text");
}
When Testing by the application by entering "How are you?" in the 1st textBox and "o" in the 2nd TextBox. I got a message like this
Conculsion:
Thanks to Microsoft for this feature, it will save the time of many programmers.
History
Keep a running update of any changes or improvements you've made here.