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.
views:
3432answers:
25String.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.
String.Join() (however, almost everyone knows about string.Split and seems to use it every chance they get...)
Many people seem to like stepping through an XML file manually to find something rather than use XPathNaviagator.
input.StartsWith("stuff") instead of Regex.IsMatch(input, @"^stuff")
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.
Hard coding a / into a directory manipulation string versus using:
IO.Path.DirectorySeparatorChar
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);
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.
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()
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
Trying to figure out where My Documents lives on a user's computer. Just use the following:
string directory =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Most people forget that Directory.CreateDirectory() degrades gracefully if the folder already exists, and wrap it with a pointless, if (!Directory.Exists(....)) call.
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);
Instead of generating a file name with a Guid, just use:
Path.GetRandomFileName()
- Using DebuggerDisplay attribute instead of ToString() to simplify the debugging.
- Enumerable.Range
- Tuples from FSharp.Core!
myString.Equals(anotherString)
and options including culture-specific ones.
I bet that at least 50% of developers write something like: if (s == "id") {...}
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.
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.