Possible Duplicate:
Is there a better alternative than this to 'switch on type'?
I need to iterate through all properties of my class and to check if its type of int the i need to do something, if its string .. then do something. I need it using switch-case. Here i am using switch in the following manner, but it asks for some constant. see the code below:
public static bool ValidateProperties(object o)
{
if(o !=null)
{
var sourceType = o.GetType();
var properties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (var property in properties)
{
var type = property.GetType();
switch (type)
{
*case typeof(int):* getting error here
// d
}
}
}
}
Also i want to know , what check should I use, typeof(int) or typeof(Int32)?
You cannot use a switch block to test values of type
Type. Compiling your code should give you an error saying something like:You’ll need to use
if–elsestatements instead.Also:
typeof(int)andtypeof(Int32)are equivalent.intis a keyword andInt32is the type name.UPDATE
If you expect that most types will be intrinsic you may improve performance by using a switch block with
Type.GetTypeCode(...).For example: