Generic Parsing, Part 2: Parse<T>

This is part 2 of a series on generic parsing. Here is part 1.

Having tackled the task of developing a generic TryParse method, it makes sense to also implement a generic Parse method, since TryParse rarely exists alone.

The infrastructure is mostly the same. The key difference, besides the method names, is that HasParseSignature and FindParseMethod check for a different signature:

static T Parse(string s);

GetParseMethod and SetParseMethod are essentially the same as their TryParse counterparts.

Not having to deal with an output parameter, the Parse methods are a little easier to implement:

public static object Parse(this string s, Type type)

{

   MethodInfo method = GetParseMethod(type);

   if (method == null)

      throw new Exception(...);

 

   return method.Invoke(null, new object[] { s });

}

 

public static T Parse<T>(this string s)

{

   return (T)Parse(s, typeof(T));

}

Be sure to check out parts 3 and 4.


Attachment: GenericParsing.zip

0 comments :: Generic Parsing, Part 2: Parse<T>

Post a Comment