Articles → CSHARP → Extension Method In C#

Extension Method In C#






Purpose





Scenario






  1. Create a custom class and add a method IsEvenNumber in it
  2. Create an extension method



Create A Custom Class




public class UsefulFunctions {
  public bool IsEvenNumber(int num) {…
  }
}











Create Extension Method




  1. Create a static class
  2. Inside the class create a static method
  3. Pass an argument of any data type of which you want to write the extension method prefixed by this keyword
public static class ExtensionMethodsClass {
  public static bool IsEvenNumber(this int num) {
    bool status = false;
    if (num % 2 == 0) {
      status = true;
    }
    return status;
  }
}




int x = 3;
MessageBox.Show(x.IsEvenNumber().ToString());





Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, February 23, 2011

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250