Thursday, September 3, 2015

C# quick extension method refresher - Left() and Right() methods

Here's a quick refresher of C#'s extension methods. If you are not familiar with or forgot about extension methods, check out this post at dotnetperls.


using System;
     
public class Program
{
 public static void Main()
 {
  Console.WriteLine("Hello World");
  
  string a = "Hello Orange County";  
  Console.WriteLine("a.Right(6) = " + a.Right(6));
  Console.WriteLine("a.Left(7) = " + a.Left(12));
 }
}

public static class ExtensionMethods
{
 public static string Right(this string original, int numChar)
 {
  string retVal = "";
  if(original != null && numChar >= 0)
  {
   return original.Substring(numChar > original.Length ? 0 : original.Length - numChar); 
  }
  return retVal;
 }
 
 public static string Left(this string original, int numChar)
 {
  string retVal = "";
  if(original != null && numChar >= 0)
  {
   return original.Substring(0, (numChar > original.Length ? original.Length : numChar));
  }
  return retVal;
 }
}

By the way, there is an amazing online C# compiler tool called ".NET Fiddle". It lets you quickly build and test your C# prototype program online, including ASP.NET MVC-based prototypes. Just like the JSFiddle, you can create your own account and start building your own personal code libraries.

Here's a review article about .NET Fiddle.

.Net Fiddle Screenshot

No comments: