Contents tagged with ExtensionMethods
Two simple Extension Methods for Reader
I have added to my Extension Methods library a very useful ForEachLine methods, that extends the TextReader and FileInfo functionality.
The purpose of those methods is simple: provides ability to provide action to invoked for each line of a TextReader of file.Here are the methods for anyone how find them useful, as well.
TextReader ForEachLine Extension Method
public static void ForEachLine(this TextReader reader, Action<string> action) {
if (reader == null)
throw new ArgumentNullException("reader");
if (action == null)
throw new ArgumentNullException("action");
string line;
while ((line = reader.ReadLine()) != null) {
action(line);
}
}
FileInfo ForEachLine Extension Method
public static void ForEachLine(this FileInfo file, Action<string> action) {
if (file == null)
throw new ArgumentNullException("file");
using (StreamReader reader = file.OpenText()) {
reader.ForEachLine(action);
}
}
Happy coding ...
DateTime.ToSiteString() Extension Method
I'm mostly using LINQ to SQL and Entity Framework recently.
As you know, the datetime database fields are returned as Nullables of type DateTime, if they allow NULL values and I found myself adding a lot of additional data class properties like:public string ModifiedString {
get {
return this.ModifiedOn.HasValue
? this.ModifiedOn.Value.ToString("dd MMM yyyy") : "";
}
}
So, I decided to wrap that an a nice Extension Method, make it once, and then just use it.
And here is what I came up with:
namespace System {
/// <summary>
///
/// </summary>
public static class XtsDate {
#region Static Fields /////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets the date format.
/// </summary>
/// <value>The date format.</value>
public static string DateFormat = "dd MMM yyyy";
#endregion
#region Static Methods ////////////////////////////////////////////////////////////////////
/// <summary>
/// Toes the site string.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
public static string ToSiteString(this DateTime date) {
return date.ToString(DateFormat);
}
/// <summary>
/// Toes the site string.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
public static string ToSiteString(this DateTime? date) {
return date.HasValue ? date.Value.ToString(DateFormat) : "";
}
#endregion
}
}
Now, when I need some DateTime field as string I just can use:
return this.ModifiedOn.ToSiteString();
Hope this helps anyone ...
Regards