I’ve been doing a decent amount of string manipulation lately and decided to combine that with my newfound knowledge about .NET extension methods. If you don’t know what extension methods are, they’re basically a way to extend a class without needing the source code to that particular class–hence why I can extend the System.String type by simply writing another class. The key is with the parameters of your methods. Here’s the basic gist of it:
So the key here is the “this” keyword before the type identifier in the parameter list of the method.
I’ve wrapped all of my extension methods into a single class simply called “ExtensionMethods” and added it to my project. The namespace doesn’t matter, so I haven’t included it in this example. You can either use the global namespace (though I don’t recommend it) or just create your own namespace called whatever you want.
Without further adue, here’s the code:
/// <summary>
/// Asserts the trailing path delimiter.
/// </summary>
/// <param name="InputPath">The input path.</param>
public static void AssertTrailingPathDelimiter(this string InputPath)
{
InputPath = InputPath.IncludeTrailingPathDelimiter();
}
/// <summary>
/// Trims the extension from a file name.
/// </summary>
/// <param name="InputFile">The input file.</param>
public static void TrimExtension(this string InputFile)
{
int start, count;
if ((start = InputFile.LastIndexOf(".")) > 0)
{
count = InputFile.Length – start;
InputFile = InputFile.Remove(start, count);
}
}
/// <summary>
/// Gets a file extension of a filename.
/// </summary>
/// <param name="InputFile">The input file.</param>
/// <returns>The file extension</returns>
public static string FileExtension(this string InputFile)
{
int start, count;
if ((start = InputFile.LastIndexOf(".")) > 0)
{
count = InputFile.Length – start;
return InputFile.Substring(start, count);
}
return string.Empty;
}
}
Now whenever you use a System.String object, you’ll be able to simply call these methods as if they were part of the System.String class. IE: string MyFileExtension = MyFilePath.FileExtension();
I’m sure I’ll add on to this as I go along.