mardi 21 septembre 2010

Be( a)ware of String.Replace method

If you're using String.Replace method, you will encounter an ArgumentException if oldValue is null or empty.

This may be annoying if you don't check the old value or don't trap this exception.

A radical workaround would be to introduce a little overload with your own static method or by extending the System.String class with a "safe" method like :
/// <summary>
/// Extensions for System.String class
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Safely replace all occurrences of specified System.String instance, with another System.String instance
/// </summary>
public static string SafeReplace(this string extendedString, string oldValue, string newValue)
{
if (string.IsNullOrEmpty(oldValue))
{
return extendedString;
}

return extendedString.Replace(oldValue, newValue);
}
}


1 commentaire:

Anonyme a dit…

Salut Florian,

félicitation ,tu es manager et en plus tu fait du c# je t’adore ;-)

je faisait une recherche sur goole et je suis tombé sur ton blog,qu'elle fu pas ma surprise en remarquant ta photo.

Samir
onesolofr@yahoo.fr