I have a generic method that works for most of my custom types. Today I’m building up unit tests. The extension fails with a type string. string comes up with two public instance properties, Length and Chars. When I call GetValue it bombs out “parameter count mismatch”.
I don’t have any need to allow a string. Can I add a constraint to my generic sufficient enough to solve the problem?
Code snippet
public static DataTable ToDataTable<T>(this List<T> items){...
//List<T> generally works...just found it failing out with string
List<string> items = new List<string> { "cookie", "apple", "whatever" };
System.Reflection.PropertyInfo[] props = typeof(string).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
foreach (var item in items)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
}
Charsis an indexer in C# terminology – but a “property with index parameters” in .NET/CLR terminology… so you can only get the value by specifying arguments. So in this case, it’s representing the indexer used here:In a
Dictionary<TKey, TValue>the indexer would be the way you’d getdictionary[key].If you only want “normal” properties, filter the list of properties by the ones where PropertyInfo.GetIndexParameters() returns an empty array.