Name of the .NET type is within a string

  • Thread starter Thread starter A.M-SG
  • Start date Start date
A

A.M-SG

Hi,

I have a .NET type within a string like "System.Int16" or "System.DateTime".

How can I parse and and check if a string contains a valid value from that
type?

I am trying to build a function like this:

IsValidType("123","System.Int16"); // Should return true
IsValidType("1a3","System.Int16"); // Should return false
IsValidType("6/21/2001","System.DateTime"); // Should return true
IsValidType("34/21/2001","System.DateTime"); // Should return false

Is there any wat to create a function like that without using a big
switch(), case element?

Thank you,
Alan
 
Hi Alan,

This method should work as long as you can call Parse(String) on the type. Note that date will return false unless you also specify the correct culture.

private bool IsValidType(string val, string typ)
{
Type t = Type.GetType(typ);
MethodInfo mi = t.GetMethod("Parse", new Type[]{typeof(String)});
try
{
object o = mi.Invoke(null, new object[]{val});
return true;
}
catch
{
return false;
}
}
 
Hi Alan,

Does Morten Wennevik [C# MVP]'s reply make sense to you? If you still have
any concern, please feel free to feedback. Thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Back
Top