C# Right String PartImplement the Right extension method. Right returns the rightmost part of a string.
is a custom extension method. It obtains the rightmost several characters of an input string. It returns them as a new string. The .NET Framework does not provide a Right method. We add one with extension method syntax.ExtensionStrings
this program implements the string type Right method using the extension method syntax. The Right method is called on a string instance. It internally returns a substring of the rightmost several characters.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.
Thus: The Main entry point can call the Right method we defined on any string type.
C# program that implements Right
static class Extensions
/// Get substring of specified number of characters on the right.
public static string Right(this string value, int length)
return value.Substring(value.Length - length);
static void Main()
const string value1 = "soft orange cat";
const string value2 = "PERLS";
string result1 = value1.Right(3);
string result2 = value2.Right(1);
The exceptions thrown
by the Right extension are similar to those thrown by the Substring method. Substring will be the source of the exceptions. If we pass a number that is too large or the input string is null, we receive an exception.
Tip: You will need to check the string length before using Right if you may have undersized strings.String Length
We implemented the string type Right method. Right returns a new 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.
And: This simple wrapper can provide a way to more effectively translate logic. It is similar to a Truncate method.Truncate String
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.