As a software developer I believe it is critical to build reusable code when possible. All software engineers have their toolbox of previously written code that they reuse when the need arises. Keeping this in mind I have built a Class Library, that I continually extend, that contains all the reusable functions that I use across multiple projects. I call this my Core.dll and include it in all the projects I work on.
The project contains multiple classes for a variety of functions, anything from string manipulation to file generation. I will be sharing little code bits from this Core library in the Bite Size C# posts.
Today we will look at my StringExtensions class, which falls in my Core.Extensions namespace.
using System; namespace Core.Extension { public static class StringExtensions { public static bool Contains(this string source, string toCheck, StringComparison comp) { return source.IndexOf(toCheck, comp) >= 0; } public static string GetLast(this string source, int tailLength) { return tailLength >= source.Length ? source : source.Substring(source.Length - tailLength); } } }
The Class contains 2 methods:
A Contains function that is similar to the built-in string.Contains method except that it takes a StringComparison parameter so that case sensitivity, culture and sort rules can be configured.
A GetLast method that passes back the requested last bit of a string (for example last 4 characters of a string.)
When this class is included in a project the following operations can be performed:
private static void Main(string[] args) { string testString = "This is a test string"; bool test = testString.Contains("STRING", StringComparison.InvariantCultureIgnoreCase); //This will return true as ignore case is set string resultString = -testString.GetLast(6); //This will return "string", the last 6 characters in the string }
This class acts as an extension class to the predefined C# string class, so its methods appear in the class method list exactly like the built-in string method do (such as string.Equals or string.Trim).