1

I'm using reflection to call a static, generic method (as the type is only known at runtime). This seems to be working well for me, until the type is of string. I get an "Object not set to an instance of the object" exception on Type proptype = entity[property.Key].GetType(); in the code below. I believe it is because at the time that it's getting the type, the string is empty.

            foreach (KeyValuePair<string, FieldAttribute> property in EntityProperties)
            {
                Type gen = typeof(DBGeneric);
                MethodInfo mi = gen.GetMethod("FromDBVal");

                Type proptype = entity[property.Key].GetType();

                MethodInfo mil = mi.MakeGenericMethod(proptype);

                object[] args = { dr[property.Value.ColumnName] };
                entity[property.Key]=mil.Invoke(null, args);
            }

dr is a datareader. EntityProperties is a dictionary populated using reflection earlier, to avoid unnecessary, repeat reflection. FieldAttribute is a custom attribute on each property of the model that specifies how that property relates back to the column of the table in the database. Here are two example properties:

    [Field("COLUMN1", "Description of this column.", true)]
    public int Property1 { get; set; }

    [Field("COLUMN2", "Description of this column.", true)]
    public string Property2 { get; set; }

The generic method I'm calling, FromDBVal<T>, mostly just handles null values in the database, but also handles some types a little differently (due to the database design, sometimes some values will be returned as decimal with a precision of .00 when they should be int32.

So can anyone see a way I can get the type where it is an empty string?

Edit:

I had already tried what the other answers were proposing and it was not working for me. I've ended up refactoring slightly, handling strings separately (also used some material from Jon Skeet's answer at https://stackoverflow.com/a/3561320/4852638).

Community
  • 1
  • 1
James D
  • 360
  • 3
  • 13
  • possible duplicate of [C# get type of null object](http://stackoverflow.com/questions/930147/c-sharp-get-type-of-null-object) – Mark Miller Jul 24 '15 at 01:36
  • Check out the answers in the dup I just posted. I think that should solve this for ya. You just need to check if the object is null before calling GetType, and if it is, handle it accordingly... maybe create a generic type object and pass it instead. – Mark Miller Jul 24 '15 at 01:40
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Preston Guillot Jul 24 '15 at 01:41
  • You should look up the properties on the entity, matching by property.Key - and use PropertyType. If the field is null, you cannot find out its type - you must check the property definition itself as I described above. – Rob Jul 24 '15 at 02:52

0 Answers0