This post will discuss how to extract rightmost n characters from a string in C#.

For example, if the string is ABC1234 and n = 4, the solution should give substring 1234.

 
Here’s a utility method that shows how to implement this with the String.Substring() method.

Download  Run Code

 
The above approach will throw an ArgumentOutOfRangeException when the string’s length is less than the total number of characters required. The following code example demonstrates how to handle this:

Download  Run Code

 
Here’s another alternative syntax that handles the case when string length is less than the total number of characters.

Download  Run Code

That’s all about extracting rightmost n characters from a string in C#.