Using Type T for making C# Method Calls More Flexible

I often find myself getting lazy and making multiple entry points for a method when I really should spend an extra 30 seconds and use the Type T pattern in C#.  Below are the two calls I had and when I started writing the one that returns int, I decided enough was enough.

private static bool GetWorkshopTopLevelPropertyBool(JToken jToken, string attr2)
{
    return jToken["workshopResults"][attr2].Value();
}

private static string GetAttendeeInfoString(JToken jToken, string attr)
{
    return jToken["attendeeResults"][attr].Value();
}

Here is the generalized verison of the same code but only has to be written once.

private static T GetAttendeeInfo(JToken jToken, string attr)
{
    return jToken["attendeeResults"][attr].Value();
}

HTH’s

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he's a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Follow

Get every new post delivered to your Inbox

Join other followers: