+92 332 4229 857 99ProjectIdeas@Gmail.com

Adding Your Own Method To int , string classes (C#.net)


Extension Methods
The following code shows you how to make extension methods, how to use them. You can make your own method and add it to int, string library and can use it wherever you want.
You must define the method to be static and also the class in which this method is implemented should also be static class. A very cool feature of c# 4.0

Code

public static class ExtensionMethodsExample
{

// Adding a WordsCount method to String Class
// this function split the string at every space and then returns how many words string have
public static int WordsCount(this string str)
{
  return str.Split(new char[] { ' ' }).Length;
}

public static void Main(string[] args)
{
  string st = "i proud to be a pakistani";
  Console.WriteLine(st.WordsCount()); // output : 6 (excluding of spaces)
}

// Adding a Tell method to int Class
// this function returns whether the number is even or odd
public static string Tell(this int no)
{
   return no % 2 == 0 ? "Even" : "Odd";
}

public static void Main(string[] args)
{
    int n = 5;
    Console.WriteLine(n.Tell()); //output : Odd

    int n = 4;
    Console.WriteLine(n.Tell()); //output : Even
}

// Adding a Factorial method to int Class
// this function returns factorial of number
public static double Factorial(this int num)
{
   double factorial = 1;

     for (int i = 1; i <= num; i++)
          factorial = factorial * i;

   return factorial;
}

public static void Main(string[] args)
{
    int n = 5;
    Console.WriteLine(n.Factorial()); //output : 120
}

// Adding a ToInteger() method to string Class
// this function returns the given string converted to integer
public static int ToInteger(this string obj)
{
   return int.Parse(obj);
}

public static void Main(string[] args)
{
    string  s = "1234";
    int n = s.ToInteger(); // Converting string to integer
}

// Adding a ToInteger() method to char Class
// this function returns the given char converted to integer
public static int ToInteger(this char obj)
{
    return int.Parse(obj.ToString());
}

public static void Main(string[] args)
{
   string  s = "1234";
   int sum = 0;

   for (int i = 0; i < s.Length; i++)
   {               
     sum += s[i].ToInteger();// converting each char to integer and sum elements of string.
   }

    Console.WriteLine(sum); // output : 10
}

0 comments: