I recently needed to mask out some characters of a credit card string so that only the last 4 were displayed. Surprisingly there doesn’t seem to be many good examples of this so I decided to put together something myself and I figured it would be more useful as an extension method.

StringExtensions.cs

public static class StringExtensions
{
	public static string Mask(this string source, int start, int maskLength)
	{
		return source.Mask(start, maskLength, 'X');
	}

	public static string Mask(this string source, int start, int maskLength, char maskCharacter)
	{
		if (start > source.Length -1)
		{
			throw new ArgumentException("Start position is greater than string length");
		}

		if (maskLength > source.Length)
		{
			throw new ArgumentException("Mask length is greater than string length");
		}

		if (start + maskLength > source.Length)
		{
			throw new ArgumentException("Start position and mask length imply more characters than are present");
		}

		string mask = new string(maskCharacter, maskLength);
		string unMaskStart = source.Substring(0, start);
		string unMaskEnd = source.Substring(start + maskLength, source.Length - maskLength);

		return unMaskStart + mask + unMaskEnd;
	}
}

IntegerExtensions.cs

public static class IntegerExtensions
{
	public static string ToStringMask(this int source, int start, int maskLength)
	{
		return source.ToString().Mask(start, maskLength, 'X');
	}

	public static string ToStringMask(this int source, int start, int maskLength, char maskCharacter)
	{
		return source.ToString().Mask(start, maskLength, maskCharacter);
	}
}

The below code will output a string with the first 12 characters replaced with “X”s.

string creditCard = "1234567891234567";
string maskedCreditCard = creditCard.Mask(0, 12);
Categories: Programming

3 Comments

sumit pitroda · 2nd March 2020 at 11:37 am

it’s perfect example for masking. i am done some changes in above code and it’s work for all type of costume masking.
thanks for giving this example.

ming · 10th July 2020 at 8:54 am

string unMaskEnd = source.Substring(start + maskLength, source.Length – maskLength);
It may be wrong, it should be changed to this way…
string unMaskEnd = source.Substring(start + maskLength);

    Shinigami · 10th July 2020 at 10:30 am

    Thanks, I think they should give the same result but your way is a bit cleaner.

Leave a Reply

Your email address will not be published. Required fields are marked *