C# - Get Last N characters from a string

A simple C# extension method which use Substring to get the last N characters in a string.

Abhith Rajan
Abhith RajanSeptember 22, 2019 · 2 min read · Last Updated:

In C#, Substring method is used to retrieve (as the name suggests) substring from a string. The same we can use to get the last ‘N’ characters of a string.

String.Substring Method

As described in String.Substring Method (System) | Microsoft Docs, Substring method has two overloads,

Substring(Int32)Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.
Substring(Int32, Int32)Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

With the starting position only overload, we can do.

1mystring.Substring(mystring.Length - N);

But the above code will fail in case mystring length is lower than the ‘N’. So considering that case, lets have an extension method,

1public static string GetLast(this string source, int numberOfChars)
3 if(numberOfChars >= source.Length)
4 return source;
5 return source.Substring(source.Length - numberOfChars);

And you can use the above like,


This extension method is now part of the Code.Library Nuget package.

Abhith Rajan

Written by Abhith Rajan
Abhith Rajan is an aspiring software engineer with more than nine years of experience and has a proven successful track record of delivering technology-based products and services.

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub

Related SnippetsView All

Related ArticlesView All

Related VideosView All

HTTP Logging in ASP.NET Core 6.0

High-performance logging in .NET, the proper way

What is Span in C# and why you should be using it

Related StoriesView All