How To Test if Type is Primitive
Posted
by DaveDev
on Stack Overflow
See other posts from Stack Overflow
or by DaveDev
Published on 2010-03-14T14:58:59Z
Indexed on
2010/03/14
15:05 UTC
Read the original article
Hit count: 387
Hi Guys
I have a block of code that serializes a type into a Html tag.
Type t = typeof(T); // I pass <T> in as a paramter, where myObj is of type T
tagBuilder.Attributes.Add("class", t.Name);
foreach (PropertyInfo prop in t.GetProperties())
{
object propValue = prop.GetValue(myObj, null);
string stringValue = propValue != null ? propValue.ToString() : String.Empty;
tagBuilder.Attributes.Add(prop.Name, stringValue);
}
This works great, except I want it to only do this for primitive types, like string, int, double, bool etc. I want it to ignore everything else.
Can anyone suggest how I do this? Or do I need to specify the types I want to allow somewhere and switch on the property's type to see if it's allowed? That's a little messy, so it'd be nice if I there was a tidier way.
© Stack Overflow or respective owner