Often we need just the rightmost few characters in a C# string
. We can implement Right()
as a custom extension method. It returns the right part as a new string
.
There is no Right()
in .NET. But we can add one with extension method syntax. This helps us translate programs from other languages that have Right.
Suppose we pass in the string "orange cat" and want just the right 3 characters. The word "cat" should be returned by Right()
.
Input: "orange cat" Right(3): "cat"
This program implements Right()
using the extension method syntax. Right is called on a string
. It internally returns a substring of the rightmost several characters.
null
character is not returned.static
class
. This is where the Right extension method is declared.Right()
is a public static
method, but the first parameter must use the "this" modifier before the type declaration.using System; static class Extensions { /// <summary> /// Get substring of specified number of characters on the right. /// </summary> public static string Right(this string value, int length) { return value.Substring(value.Length - length); } } class Program { static void Main() { const string value1 = "orange cat"; const string value2 = "PERLS"; string result1 = value1.Right(3); string result2 = value2.Right(1); Console.WriteLine(result1); Console.WriteLine(result2); } }cat S
The exceptions thrown by the Right extension are similar to those thrown by the Substring
method. Substring
will be the source of the exceptions.
null
, we receive an exception.string
length before using Right if you may have undersized strings.Right returns a string
instance containing the specified number of characters starting from the final character index. The Right method is not built into the .NET string
type.