Checking for variable type

P

Pavils Jurjans

Hello,

I am writing a data serialization routine, and need to determine the value
type for each element in given hashtable. Number types should be treated in
one way, string and char types in other way, regex type in other, and arrays
in just another. Now I am quite confused about what could be the best
strategy for this type checking. Of course, I can do
myVar.getType().ToString() to get the full type identifier. But, I'd be
happy for some kind of "isNumeric" method that would straightforward give
feedback whether the given type is nueric one. Arrays could be checked by
comparing with the IList interface.
So, among all the different choices, what would be the best way?

Thanks,

Pavils
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Pavils,

IMHO you should check the Type objects for the values.

e.g. if(typeof(char) == value.GetType())
{
//char
}
else if(typeof(string) == value.GetType())
{
//string
}

infortuantely AFAIK there is no IsNumber like method so you should chack
against different number type Type objects.

If you want to filter down all objects implementing given interface (IList
for example)
you can use the following

if(typeof(IList).IsAssignableFrom(value.GetType()))
{
//List
}
 
E

Ed Courtenay

Stoitcho said:
If you want to filter down all objects implementing given interface (IList
for example)
you can use the following

if(typeof(IList).IsAssignableFrom(value.GetType()))
{
//List
}

Or the much less verbose:

if (value is IList)
{
// List
}
 
P

Pavils Jurjans

Hello Stoitcho,
IMHO you should check the Type objects for the values.

e.g. if(typeof(char) == value.GetType())
{
//char
}
else if(typeof(string) == value.GetType())
{
//string
}


if(typeof(IList).IsAssignableFrom(value.GetType()))
{
//List
}

Cool, thanks, I will go that route.

Isn't this the same as {value is IList } ?

Rgds,

Pavils
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Pavils,
Yes, they are almost the same. The only difference is that with *is*
operator the type is always hard coded. Using IsAssignableFrom the type
objects can be stored in some kind of collection, thus more extendable. I
agree that I should've given better example. Anyways if you want to hardcode
the types using *is* is more readable.

There is one more thing. *is* operator does actual type casting where
IsAssignableFrom doesn't have to do that. You shouldn't be concerned about
the performance in this case, but it is possible that IsAssignableFrom is
better performance wise. This is only a guess and I may be wrong. Hoewever
this is not important I believe.
 

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