tags:

views:

340

answers:

3
typeof(string).IsPrimitive == false
typeof(int).IsPrimitive == true
typeof(MyClass).IsClass == true
typeof(string).IsClass == true
typeof(string).IsByRef == false
typeof(MyClass).IsByRef == true

I have a method that instantiates a new instance of T and, if it's a "complex" class, fills its properties from a set of source data values.

(a) If T is a simple type (e.g. a string or an int or anything else similar), a quick conversion from the source data to T is to be performed.

(b) If T is a class (but not something simple like string), then I'll use Activator.CreateInstance and do a bit of reflection to populate the fields.

Is there a quick and simple way to tell if I should use method (a) or method (b)? This logic will be used inside a generic method with T as the type argument.

+9  A: 

String is probably a special case.

I think I would do

Type type = typeof(T);
if (type.IsPrimitive || type.Equals(typeof(string))
{
  // simple case ...
}
else
{
  // complex case
}
Stefan Steinegger
John Saunders, below, makes a valid point, so in that light I think your answer is probably the best one for my case.
Nathan Ridley
A: 

Strings aren't primitives, if I recall correctly. even though there is a keyword for it, a string is an object. Your call to IsPrimitive will accurately tell you if something is a primitive.

Annath
Yes but strings are assigned like primitives and in most cases are treated (from the outside) as though they are primitives.
Nathan Ridley
Strings are kind of a unique beast in this regard. I think Stefan's suggestion of special handling for them is the best approach.
Reed Copsey
+1  A: 

It may not matter, but it sounds like you're leaving out a few cases:

  1. Complex types which have conversions
  2. Value types which don't have a parameterless constructor. Example below:

There are probably more, but I think you're partitioning the problem space in an overly-restrictive manner.

 public class Person {
    private string _name;
    private int _age;
    public Person(string name, int age) {_name = name; _age = age;}
    // Remainder of value implementation
 }
John Saunders
Could you give me an example of case #2?
Nathan Ridley