Home
Map
String Right PartImplement the Right extension method. Right returns the rightmost part of a string.
C#
This page was last reviewed on Sep 11, 2023.
Right. 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.
Method notes. 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.
Extension
Input and output. 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"
Example code. 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.
String Substring
Then Right(3) will return the final 3 characters in the string. Like other C# strings, the null character is not returned.
Here The program introduces the Extensions static class. This is where the Right extension method is declared.
Info 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
Exceptions. The exceptions thrown by the Right extension are similar to those thrown by the Substring method. Substring will be the source of the exceptions.
Tip If we pass a number that is too large or the input string is null, we receive an exception.
Tip 2 You will need to check the string length before using Right if you may have undersized strings.
String Length
A summary. 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.
String Truncate
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.