C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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 = "soft orange cat";
const string value2 = "PERLS";
string result1 = value1.Right(3);
string result2 = value2.Right(1);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
}
Output
cat
S
Tip: You will need to check the string length before using Right if you may have undersized strings.
String LengthAnd: This simple wrapper can provide a way to more effectively translate logic. It is similar to a Truncate method.
Truncate String