Demonstrate the extension methods - CSharp Custom Type

CSharp examples for Custom Type:Extension Methods

Description

Demonstrate the extension methods

Demo Code

using System;/*from w w  w  .j a  v  a2  s. c  o  m*/
class Program
{
   static void Main(string[] args)
   {
      string target = "0123456789";
      Console.WriteLine("Original target string: {0}", target);
      Console.WriteLine("Left 3 chars (012): {0}", target.Left(3));
      Console.WriteLine("Right 3 chars (789): {0}", target.Right(3));
      Console.WriteLine("Mid for 3 chars starting at index 4 in target (456): {0}", target.Mid(4, 3));
      Console.WriteLine("Take a slice equivalent to previous Mid() call: {0}", target.Slice(4, 6));
   }
}
public static class MyStringExtensions
{
   public static string Left(this string target, int numberOfCharsToGet)
   {
      return target.Substring(0, numberOfCharsToGet);
   }
   public static string Right(this string target, int numberOfCharsToGet)
   {
      return target.Substring(target.Length - numberOfCharsToGet, numberOfCharsToGet);
   }
   public static string Mid(this string target, int startIndex, int numberOfCharsToGet)
   {
      if (startIndex < 0)
      {
         throw new ArgumentOutOfRangeException("Mid: Negative start parameter.");
      }
      return target.Slice(startIndex, startIndex + numberOfCharsToGet - 1);
   }
   public static string Slice(this string target, int startIndex, int endIndex)
   {
      if (startIndex < 0)
      {
         return target.Substring(target.Length - System.Math.Abs(startIndex), endIndex);
      }
      return target.Substring(startIndex, endIndex - startIndex + 1);
   }
}

Result


Related Tutorials