Best Practice and Development Tip: Don’t Reinvent the Wheel in C#

by Xavier Comments: 0

This is just a quick tip and development best practice based on a few things I’ve found while fixing bugs in an application. It is not just a quick tip on how to get the extension of a file, but instead it is about not reinventing the wheel, thinking about all possibilities and outcomes when you are programming and in general doing things right.

The idea is that whenever you have a problem to solve, for example get the extension for a given file you should find the appropriate framework function instead of trying to solve it on your own. Someone definitively already spent a lot of time creating a function that tests many potential scenarios.

Here is what I found:

Don't reinvent the wheel

What is the problem? That for any file that is included with multiple “.” Then as you can see the extension is extracted incorrectly.

How should I handle this? Welll, if you are wondering “oh look for the first “.” but from right to left!”

Hmmmm yes…maybe… but no sale.

Instead you should use the appropriate framework libraries. Read this:

Path.GetExtension Method

.NET Framework 4.5

7 out of 10 rated this helpful – Rate this topic

Returns the extension of the specified path string.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)



public static string GetExtension(        string path)



Type: System.String

The path string from which to get the extension.

Return Value

Type: System.String
The extension of the specified path (including the period “.”), or null, or String.Empty. If path is null, GetExtension returns null. If path does not have extension information, GetExtension returns String.Empty.

And try to do the same always. Think about all possibilities and when possible try to find out if you are not reinventing the wheel.