Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# String Right

This C# article implements the Right extension method. Right returns the rightmost part of a string.

Right 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.

Extension Method

Example. First, 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.

Then: Right(3) will return the final three characters in the string. Like other C# strings, the null character is not returned.

C# program that implements Right

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 = "The Developer Blog";
	const string value2 = "SAM ALLEN";
	string result1 = value1.Right(5);
	string result2 = value2.Right(1);



The program introduces the Extensions 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.

Then: The Main entry point can call the Right method we defined on any string type.

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

Summary. 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