Name of the .NET type is within a string

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
 
M

Morten Wennevik

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;
}
}
 
J

Jeffrey Tan[MSFT]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top