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.

+19  A: 


James Curran
Uses reflection => slow
Michael Damatov
"reflection => slow" is a ridiculous generalization and oversimplification. To use the type, the assembly must be already loaded into memory. Hence, the "reflection" used here is just getting an reference to an existing array. You could not do better rolling your own.
James Curran
Toro, why do you program .NET at all? It's slow..
Valentin Vasiliev
+21  A: 


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.

@Stimpy, string.Format() is better for localization.
Robert S.
This is not localization, this is replacing correct data with wrong data. If something is £5 you should show £5, not $5. £5 is not $5.
Dour High Arch
+32  A: 


James Curran
Although there was some hoopla about IsNullOrEmpty breaking if in nested loops a couple of years ago...
Omar Kooheji
I'm not so sure I remember anything of the sort, I've used it in fairly nested loops and algorithms since .NET 1.0
...now you tell me!
I like to create an "IsNullOrEmpty" [and "IsNotNullOrEmpty"] extension method for strings... does that count as reinventing?
Seth Petry-Johnson
Does IsNullOrEmpty() check if the string.Trim() == string.empty as well?
@KallDrexx I think they were planning to add the whitespace-only check in c# 4
Ed Woodcock
@KallDrexx: No, it does a simple check against `null` and `Length == 0`
@KallDrexx There is (atleast in .NET 4.0) a method called String.IsNullOrWhitespace()
Daniel Joseph
+14  A: 

String.Join() (however, almost everyone knows about string.Split and seems to use it every chance they get...)

James Curran
Why would I use String.Join over a plus sign?
I'm guessing you are confusing String.Join (http://msdn.microsoft.com/en-us/library/57a79xd0.aspx) with String.Concat. (Plus is an alias for the latter.)
James Curran
+1. It's silly how often I see someone reinvent the wheel by creating a StringBuilder, making a boolean for isFirstElement, and foreaching through a collection, prepending ", " before each element except the first. Just add the items to a List<string>, then call ToArray() and string.Join().
Joe White
+8  A: 


James Curran
BAH! Regex is FRIGGEN AWESOME. Away with your dismissive comment!
+4  A: 

Many people seem to like stepping through an XML file manually to find something rather than use XPathNaviagator.

James Curran
I always like to read the XML into a datatable then filter on that. Lovely, lovely datatables!
I'm not familar with XML -> DataTables. Doesn't it require that the XML be one tiered (mean that XML was a poor choice for the data to start with)
James Curran
+6  A: 

input.StartsWith("stuff") instead of Regex.IsMatch(input, @"^stuff")

except input.StartsWith() will perform about 10x better. YAGNI and KISS!
Jeff Atwood
Hah! Right you are. Edited to put them in the right order.
Not only that, but StartsWith() has nice semantics built-in - the person reading this knows exactly what is intended.
Jason Bunting
Upmodding for the comments, not the post...
Why would you resort to RegEx when there is already a method to do exactly what you need?
Jon Tackabury
+30  A: 
Path.GetFileNameWithoutExtension(string path)

Returns the file name of the specified path string without the extension.


Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.

Does GetTempFileName really create a zero-byte file on disk? What a poorly named method if that is the case....
It avoids race conditions (which could be a security hole) -- once it's returned the filename, it's guaranteed to exist.
Roger Lipscombe
The method is still poorly named. Let's invent method Path.CreateTempfile() which returns a temporary filename but doesn't actually create the file. It'll be bad because of race conditions, but it'll be as perfectly well named as GetTempFileName.
Windows programmer
+13  A: 

Hard coding a / into a directory manipulation string versus using:

John Chuckran
Why not Path.Combine and ignore DirectorySeparatorChar altogether.
there have been situations where I've needed the character alone
Although there is no real disadvantage putting a "/" instead of bothering with long variable name. No one cares about Mono 99% of the time anyway. And I don't see any other good reason to use it.
dr. evil
"/" would work fine in Mono. It's "\" that's Windows-specific (though "/" works for most WinAPIs too).
Joe White
+5  A: 

File stuff.

using System.IO;



File.Move(currentLocation, newLocation);



System.IO.FileStream file = System.IO.File.Create(fullFilePath);
David Basarab
+4  A: 

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.

I think you meant System.IO.File.ReadAllText, System.IO.File.WriteAllText.
Richard Nienaber
+41  A: 

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()

Same for File.ReadAllText and File.WriteAllText
I think that i must be one of the 5 people that actually use those off the vat!
Nice one. I just learned something new.

Path.Append is always forgotten in stuff I have seen.

There is no such method. Do you mean Path.Combine?
Seb Nilsson
+11  A: 

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

See the StringWriter class too!
David Kemp
+7  A: 

See Hidden .NET Base Class Library Classes

John Sheehan
+16  A: 

Trying to figure out where My Documents lives on a user's computer. Just use the following:

string directory =
Peter Walke
In VB.Net: My.Computer.FileSystem.SpecialFolders.MyDocuments
Joel Coehoorn
+22  A: 

The System.Diagnostics.Stopwatch class.

John Nolan
+4  A: 

Most people forget that Directory.CreateDirectory() degrades gracefully if the folder already exists, and wrap it with a pointless, if (!Directory.Exists(....)) call.

James Curran
This is untrue. In ASP.NET 2.0 (my test), Directory.CreateDirectory(some path) will throw an exception if the directory already exists.
Redbeard 0x0A
+8  A: 
Romain Verdier
+16  A: 

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);
Bobby Ortiz
+4  A: 

Instead of generating a file name with a Guid, just use:

Ed Ball
+5  A: 
Rinat Abdullin


and options including culture-specific ones.

I bet that at least 50% of developers write something like: if (s == "id") {...}

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. http://msdn.microsoft.com/en-us/library/362314fe%28VS.80%29.aspx
+5  A: 

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 ).


//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.

+1  A: 

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.

Joel Coehoorn