The C# cast operator (Type)value is pretty verbose.
When you work with COM, extenal APIs, DataSets or other not well-OOPed infrastractures, you often get an expected type as object (i.e. you know the runtime-type of the variable is string, but it's object at compile-time).
Here is an example of many castings in one-line:
IEntity entity = (IEntity)GetObjectById("Customer", 34);
string name = (string)entity.GetField("Name");
int length = name.Length;
Or as a one-liner, you really get confused with the parenthesis:
int len = ((string)((IEntity)GetObjectById("Customer", 34)).GetField("Name")).Length;
With this extension you can make the code a bit more readable:
IEntity entity = GetObjectById("Customer", 34).As<IEntity>();
string name = entity.GetField("Name").As<string>();
int length = name.Length;
int len = GetObjectById("Customer", 34).As<IEntity>().
GetField("Name").As<string>().
Length;
Here is the extension:
/// <summary>
/// Directly casts an object to a desired type.
/// </summary>
public static T As<T>(this object value)
{
return (T)value;
}
There is actually nothing sophisticated in this, and cost much more performance (calling an extension method).
But is useful for certain scenarios.
A short performance test shws that using the cast operator is about as twice as faster than the function:
static void Main(string[] args)
{
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
object myInt = 34;
int theInt = myInt.As<int>();
}
watch.Stop();
long elapsedAs = watch.ElapsedTicks;
watch = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
object myInt = 34;
int theInt = (int)myInt;
}
watch.Stop();
long elapsedCast = watch.ElapsedTicks;
Console.WriteLine("As function took {0} ticks", elapsedAs);
Console.WriteLine("Cast operator took {0} ticks", elapsedCast);
}
Results:
As function took 645276 ticks
Cast operator took 294869 ticks