Have u ever needed to extend a string? [Extension Methods]

Published Thursday, December 27, 2007 6:34 AM

well it's not inheritable by default so you can not extend it. that used to be the case before c# 3.0

now you can specify all the functionality that you need in an Extension Method. problem lies in that the extension method needs to access the instance of the object you are extending

well, it goes like this

1- first you declare a static class with ur static extension method an extension method is defined by the first parameter refering to the instance of the object it's going to extend using the Keyword this (note to implement your complicated algorithm to validate an Email :) )

   1: public static class StringExtension
   2: {
   3:     // note the use of this in the parameter
   4:     public static bool IsEmail(this string s){
   5:         if (s.IndexOf("@") > 0)
   6:         {
   7:             return true;
   8:         }else {
   9:             return false;
  10:         }
  11:     }
  12: }

2- In ur using list on the top of ur file includer the name of the CLASS yes the name of the class not its name space it would look like this
 

   1: using System.Web;
   2: using System.Text;
   3: using Sytem.IO;
   4: // and
   5: using StringExtension;

3- Now whenever u have a string instance that you are using you'll find an extension method added

extension

 

nice isn't it

 

update: 2 jan 2008

this is a practical example

 

Filed under: ,

Comments

# DotNetKicks.com said on Friday, December 28, 2007 5:41 PM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# sirrocco said on Friday, December 28, 2007 11:42 PM

Not that nice. Why does the String class need to know about emails ?

The validator of employee should know that firstName should be an email and validate accordingly .

# amir.magdy said on Saturday, December 29, 2007 5:17 AM

actually this was just a dumb example to show extension methods you can do a lot of way :) nicer stuff

with extension methods

# sirrocco said on Saturday, December 29, 2007 11:16 AM

the problem is that allot of people take examples like this to hart :D .... and all kind of nasty things happen.

# amir.magdy said on Saturday, December 29, 2007 1:32 PM

sorry for them and for you :D

won;t do it again

# Amr EL-Garhy said on Friday, January 11, 2008 11:01 AM

Based on sirrocco comment

So what will be the ideal use of this string Extension, when should i think to use it in real application?

want to know its benefit.

# amir.magdy said on Sunday, January 13, 2008 12:18 AM

things that are string related like fixing capitalization or remvoving diacritics and so ...

# Amr ElGarhy said on Monday, March 17, 2008 8:34 AM

Found a good post about the same idea as yours, with some more sample:

www.c-sharpcorner.com/.../ExtendingStringClass.aspx

Leave a Comment

(required) 
(required) 
(optional)
(required) 

This Blog

Syndication