Insane C# Development

Montag, Mai 25, 2009

Most valueable C# extension methods


A dump of my most valueable extension methods in C#:

public static bool IsNullOrEmptyTrimmed(this string value)
{
return (value == null || value.Trim().Length == 0);
}


// if( param.IsEither( “KTB”, “KTC”, “CTC”)) { … }
// <T> instead of just sticking to IComparable[] for type safety!

public static bool IsEither<T>(this T value, params T[] possibleValues) where T : IComparable
{
for (int i = 0; i < possibleValues.Length; i++)
{
if (value.CompareTo(possibleValues[i]) == 0)
{
return true;
}
}

return false;
}

// if( val.IsNeither( param1, param2, param3)) { … }
// <T> instead of just sticking to IComparable[] for type safety!

public static bool IsNeither<T>(this T value, params T[] possibleValues) where T : IComparable
{
return !IsEither(value, possibleValues);
}

// dataField = userString.GetAtMost( 30);
public static string GetAtMost(this string value, uint countCharacters)
{
return value.GetAtMost(0, countCharacters);
}


// dataField = userString.GetAtMost( 10, 30);
public static string GetAtMost(this string value, uint startIndex, uint countCharacters)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
else
{
return value.Substring((int)startIndex,
Math.Min((int)countCharacters, value.Length - (int)startIndex));
}
}

// uint val = userString.SafeConvert( 0u);
public static uint SafeConvert(this string value, uint defaultValue)
{
uint outVal;
if (uint.TryParse(value, out outVal))
{
return outVal;
}
else
{
return defaultValue;
}
}


// int val = userString.SafeConvert( -1);
public static int SafeConvert(this string value, int defaultValue)
{
int outVal;
if (int.TryParse(value, out outVal))
{
return outVal;
}
else
{
return defaultValue;
}
}


// handy if you have to interface with non-generics code
// (LINQ won’t help you here!)

public static T[] ToArray<T>(this System.Collections.ICollection collection)
{
T[] retVal = new T[collection.Count];
collection.CopyTo(retVal, 0);
return retVal;
}

Labels: