Friday, July 17, 2009

Coalesce Follow Up

My earlier post on creating your own Coalesce function only deals with strings, I realised belatedly… here’s a ‘generic’ version that works with other types;

#region Coalesce Overloads

/// <summary>
///
Returns the first value from the collection that does not match the default for the specified type, or else the default for the specified type.
/// </summary>
/// <remarks>
/// <para>
For the set of integers 0, 10, 5, 6 this function will return 10, as it is the first integer in the set that is not 0.</para>
/// <para>
For the set of nullable integers null, 0, 10, 5, 6 this function will return 0, as it is the first integer in the set that is not null.</para>
/// </remarks>
/// <typeparam name="T">
The type of values being compared.</typeparam>
/// <param name="values">
A set of values to find the first non-default value in.</param>
/// <returns>
The first value from the set that is not the default value for the type specified, or else the default for the specified type.</returns>
public static T Coalesce<T>(params T[] values)
{
return Coalesce((IEnumerable<T>)values);
}

/// <summary>
///
Returns the first value from the collection that does not match the default for the specified type, or else the default for the specified type.
/// </summary>
/// <remarks>
/// <para>
For the set of integers 0, 10, 5, 6 this function will return 10, as it is the first integer in the set that is not 0.</para>
/// <para>
For the set of nullable integers null, 0, 10, 5, 6 this function will return 0, as it is the first integer in the set that is not null.</para>
/// </remarks>
/// <typeparam name="T">
The type of values being compared.</typeparam>
/// <param name="values">
A <see cref="System.Collections.IEnumerable"/> set of values to find the first non-default value in.</param>
/// <returns>
The first value from the set that is not the default value for the type specified, or else the default for the specified type.</returns>
public static T Coalesce<T>(IEnumerable<T> values)
{
T defaultValue = default(T);
T retVal = default(T);
foreach (T testValue in values)
{
if (testValue != null && !testValue.Equals(defaultValue))
{
retVal = testValue;
break;
}
}

return retVal;
}

#endregion


Technorati Tags: ,,,

No comments:

Post a Comment