A better switch with Lambdas in .NET, Part 4 (Working with Types)
By | September 24, 2013

When dealing with the new Switch case constructs, I always wanted to add more to it. After adding things to it like, replacing the previous switch /case with lambdas, then adding a StringComparer and then adding IComparer, I thought let us add something really useful to it. The switch with Types is always one might have wanted with traditional switches. Here is an implementation of Switch/Case constructs using lambdas to enumerate type of an object.

Let us define a Switch/Case that can enumerate the typeof an object.

public class TypeSwitcher
{
public class CaseInfo
{
public Type Case { get; set; }
public Action TargetAction { get; set; }
public bool IsDefault { get; set; }
}

public static void Me(object source, params CaseInfo[] cases)
{
Type stype = source.GetType();
CaseInfo defaultCase = null;
bool isTargetActionTaken = false;
foreach (var entry in cases)
{
if (entry.IsDefault)
defaultCase = entry;

if (!entry.IsDefault && entry.Case.Equals(stype))
{
entry.TargetAction(stype);
isTargetActionTaken = true;
break;
}
}
if (!isTargetActionTaken && defaultCase != null)
defaultCase.TargetAction(stype);

}
public static CaseInfo Case(Type source, Action action)
{
return new CaseInfo { TargetAction = x => action(), Case = source };
}
public static CaseInfo Default(Action action)
{
return new CaseInfo { TargetAction = x => action(), IsDefault = true };
}
}

Here the above code gets an object in static method Me and gets its type and passes it to the Cases. The case with its exact match of Type will execute.

To try this we use the following code :

string type = "abhishek";
TypeSwitcher.Me(type,
new TypeSwitcher.CaseInfo
{
Case = typeof(int),
TargetAction = e =>
{
Console.WriteLine("Integer...");
}
},
new TypeSwitcher.CaseInfo
{
Case = typeof(string),
TargetAction = e =>
{
Console.WriteLine("String...");
}
},
new TypeSwitcher.CaseInfo
{
Case = typeof(double),
TargetAction = e =>
{
Console.WriteLine("Double...");
}
},
new TypeSwitcher.CaseInfo
{
IsDefault = true,
TargetAction = e =>
{
Console.WriteLine("Default...");
}
});

Console.ReadKey(true);

Clearly you can see the Switch/case construct has been enabled, such that it identifies the appropriate switch automatically and calls the Switch with String type.

I hope this code will come handy.

Happy programming.

One thought on “A better switch with Lambdas in .NET, Part 4 (Working with Types)

  1. Pingback: acheter

Comments are closed.