Most useful .NET utility classes developers tend to reinvent rather than reuse
.Net.Net Problem Overview
I recently read this Phil Haack post (The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse) from last year, and thought I'd see if anyone has any additions to the list.
.Net Solutions
Solution 1 - .Net
People tend to use the following which is ugly and bound to fail:
string path = basePath + "\\" + fileName;
Better and safer way:
string path = Path.Combine(basePath, fileName);
Also I've seen people writing custom method to read all bytes from file. This one comes quite handy:
byte[] fileData = File.ReadAllBytes(path); // use path from Path.Combine
As TheXenocide pointed out, same applies for File.ReadAllText()
and File.ReadAllLines()
Solution 2 - .Net
String.IsNullOrEmpty()
Solution 3 - .Net
Path.GetFileNameWithoutExtension(string path)
Returns the file name of the specified path string without the extension.
Path.GetTempFileName()
Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.
Solution 4 - .Net
The System.Diagnostics.Stopwatch
class.
Solution 5 - .Net
String.Format.
The number of times I've seen
return "£" & iSomeValue
rather than
return String.Format ("{0:c}", iSomeValue)
or people appending percent signs - things like that.
Solution 6 - .Net
Enum.Parse()
Solution 7 - .Net
String.Join() (however, almost everyone knows about string.Split and seems to use it every chance they get...)
Solution 8 - .Net
Trying to figure out where My Documents lives on a user's computer. Just use the following:
string directory =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Solution 9 - .Net
I needed to download some files recently in a windows application. I found the DownloadFile method on the WebClient object:
WebClient wc = new WebClient();
wc.DownloadFile(sourceURLAddress, destFileName);
Solution 10 - .Net
Hard coding a / into a directory manipulation string versus using:
IO.Path.DirectorySeparatorChar
Solution 11 - .Net
The StringBuilder class and especially the Method AppendFormat.
P.S.: If you are looking for String Operations performance measurement: StringBuilder vs. String / Fast String Operations with .NET 2.0
Solution 12 - .Net
Environment.NewLine
Solution 13 - .Net
Instead of generating a file name with a Guid, just use:
Path.GetRandomFileName()
Solution 14 - .Net
Lots of the new Linq features seem pretty unknown:
Any<T>() & All<T>()
if( myCollection.Any( x => x.IsSomething ) )
//...
bool allValid = myCollection.All(
x => x.IsValid );
ToList<T>(), ToArray<T>(), ToDictionary<T>()
var newDict = myCollection.ToDictionary(
x => x.Name,
x => x.Value );
First<T>(), FirstOrDefault<T>()
return dbAccessor.GetFromTable( id ).
FirstOrDefault();
Where<T>()
//instead of
foreach( Type item in myCollection )
if( item.IsValid )
//do stuff
//you can also do
foreach( var item in myCollection.Where( x => x.IsValid ) )
//do stuff
//note only a simple sample - the logic could be a lot more complex
All really useful little functions that you can use outside of the Linq syntax.
Solution 15 - .Net
- Using DebuggerDisplay attribute instead of ToString() to simplify the debugging.
- Enumerable.Range
- Tuples from FSharp.Core!
Solution 16 - .Net
System.Text.RegularExpressions.Regex
Solution 17 - .Net
input.StartsWith("stuff")
instead of Regex.IsMatch(input, @"^stuff")
Solution 18 - .Net
Solution 19 - .Net
For all it's hidden away under the Microsoft.VisualBasic namespace, TextFieldParser is actually a very nice csv parser. I see a lot of people either roll their own (badly) or use something like the nice Fast CSV library on Code Plex, not even knowing this is already baked into the framework.
Solution 20 - .Net
File stuff.
using System.IO;
File.Exists(FileNamePath)
Directory.Exists(strDirPath)
File.Move(currentLocation, newLocation);
File.Delete(fileToDelete);
Directory.CreateDirectory(directory)
System.IO.FileStream file = System.IO.File.Create(fullFilePath);
Solution 21 - .Net
System.IO.File.ReadAllText
vs writing logic using a StreamReader for small files.
System.IO.File.WriteAllText
vs writing logic using a StreamWriter for small files.
Solution 22 - .Net
Many people seem to like stepping through an XML file manually to find something rather than use XPathNaviagator.
Solution 23 - .Net
Most people forget that Directory.CreateDirectory() degrades gracefully if the folder already exists, and wrap it with a pointless, if (!Directory.Exists(....)) call.
Solution 24 - .Net
myString.Equals(anotherString)
and options including culture-specific ones.
I bet that at least 50% of developers write something like: if (s == "id") {...}
Solution 25 - .Net
Path.Append is always forgotten in stuff I have seen.