C# String Right

String type

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

The C# programming language

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.

Substring
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 = "dot net perls";
	const string value2 = "SAM ALLEN";
	string result1 = value1.Right(5);
	string result2 = value2.Right(1);
	Console.WriteLine(result1);
	Console.WriteLine(result2);
    }
}

Output

perls
N
Main method

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.

Exception

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

C# programming language

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

C#: String