Skip to content

Using Type T for making C# Method Calls More Flexible

Updated: at 09:24 PM

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();