Some handy String extension methods

Extension methods - don't we all just love them. If you've been out of the .Net 3.5 loop, here's some catching up - Extension Methods (C# Programming Guide). I thought i'd share some handy string extension methods i've come to love during my experience with C# 3.0. I've never been quite fond of the static String.IsNullOrEmpty method, but thanks to extension methods i can now turn it into an instance method as extension methods can be called on null values as well.

public static class StringExtensions
{
 public static string GetValueOrEmpty(this string @string)
 {
  return @string.IsNullOrEmpty() ? String.Empty : @string;
 }

 public static string ToSingleLine(this string @string)
 {
  if(@string.IsNullOrEmpty())
   return String.Empty;

  string singleLineString = @string.Replace(Environment.NewLine, " ");
  return singleLineString;
 }

 public static bool IsNullOrEmpty(this string @string)
 {
  return String.IsNullOrEmpty(@string);
 }
}

If you have any nifty extension methods that you'd be willing to share, let the readers know through the comments.


Peace,
Mihkel

1 comments:

Unknown said...

I have two methods for strings that are quite similar to yours:
IsNotNullOrEmpty { return !string.IsNullOrEmpty(source); }
and
EmptyIfNull { return source ?? string.Empty; }

For IEnumerable-s, the most useful timesavers for me have been .IsEmpty() and .EmptyIfNull<T>(). The first one uses the Linq extension method Count() and the second one returns an empty list of type T.

I also have two generic methods for all objects, which proved useful in my current project:

public static bool IsNull<T>(this T source)
{
return Equals(source, default(T));
}

public static T DefaultIfNull<T>(this T source) where T : class, new()
{
return source ?? new T();
}