-1

I'm debugging someone else's source code, and I'm not really sure how it works, so am a bit stuck.

This code:

List<string> source = new List<string>();
for (int ordinal = 0; ordinal < dbDataReader.FieldCount; ++ordinal)
    source.Add(dbDataReader.GetName(ordinal));
var list = source.Select(n => new {
                                    n = n,
                                    prop = props.FirstOrDefault<DB.PropInfo<T>>((Func<DB.PropInfo<T>, bool>)(p => string.Equals(p.Name, n, StringComparison.Ordinal)))
                                    ?? props.FirstOrDefault<DB.PropInfo<T>>((Func<DB.PropInfo<T>, bool>)(p => string.Equals(p.Name, n, StringComparison.OrdinalIgnoreCase)))
                                  }
                        )
                 .Select(param0 => new { Name = param0.n, Property = param0.prop })
                 .ToList();

while (dbDataReader.Read())
{
    T instance = Activator.CreateInstance<T>();
    foreach (var data in list)
        data.Property.Setter(instance, Convert.ChangeType(dbDataReader[data.Name], data.Property.Type)); // ERROR HERE
    objList.Add(instance);
}

throws this exception:

ArgumentException: Static property requires null instance, non-static property requires non-null instance. Parameter name: property

The variables instance and data all have what look like valid values.

What is wrong here, please?

waka
  • 3,362
  • 9
  • 35
  • 54
radders
  • 923
  • 8
  • 29
  • 1
    Seems like you're including a `static` property in your list. If it's undesired, filter it out. If it is, you need to pass `null` to the setter instead of `instance` – haim770 Oct 25 '17 at 09:00
  • data.Property is of type private class PropInfo { public string Name { get; set; } public Action Setter { get; set; } public Type Type { get; set; } } so not static. – radders Oct 25 '17 at 09:05
  • Passing null instead of instance yields: error CS1503: Argument 1: cannot convert from '' to 'T' – radders Oct 25 '17 at 09:07
  • Seems like internally, your `Action` is calling `PropertyInfo.SetValue`. Again, for a `static` property, you'll have to pass `null` instead of `instance`. How does your `Action` look like? – haim770 Oct 25 '17 at 09:07

2 Answers2

0

What about a quick dirty fix?

foreach (var data in list)
{
    try
    {
        data.Property.Setter(instance, Convert.ChangeType(dbDataReader[data.Name], data.Property.Type));
    }
    catch(ArgumentException e)
    {
        data.Property.Setter(default(T), Convert.ChangeType(dbDataReader[data.Name], data.Property.Type));
    }
}
Al Kepp
  • 5,831
  • 2
  • 28
  • 48
0

Ok, so I found the problem. It was actually within the Setter itself - the code I was given wasn't the latest version... ;-( Thanks for all the suggestions.

radders
  • 923
  • 8
  • 29