Resolving a member name at runtime - c#

Given a type, a name and a signature, how can I do a member lookup of the member with name name and signature signature using the C# rules of 7.4 (the 7.4 is the chapter number from the C# Language Specification) (or at least part of them... Let's say I can live with an exact match, without conversions/casts) at runtime? I need to get a MethodInfo/PropertyInfo/... because then I have to use it with reflection (to be more exact I'm trying to build an Expression.ForEach builder (a factory able to create an Expression Tree that represent a foreach statement), and to be pixel-perfect with the C# foreach I have to be able to do duck-typing and search for a GetEnumerator method (in the collection), a Current property and a MoveNext method (in the enumerator), as written in 8.8.4)
The problem (an example of the problem)
class C1
{
public int Current { get; set; }
public object MoveNext()
{
return null;
}
}
class C2 : C1
{
public new long Current { get; set; }
public new bool MoveNext()
{
return true;
}
}
class C3 : C2
{
}
var m = typeof(C3).GetMethods(); // I get both versions of MoveNext()
var p = typeof(C3).GetProperties(); // I get both versions of Current
Clearly if I try typeof(C3).GetProperty("Current") I get an AmbiguousMatchException exception.
A similar but different problem is present with interfaces:
interface I0
{
int Current { get; set; }
}
interface I1 : I0
{
new long Current { get; set; }
}
interface I2 : I1, I0
{
new object Current { get; set; }
}
interface I3 : I2
{
}
Here if I try to do a typeof(I3).GetProperties() I don't get the Current property (and this is something known, see for example GetProperties() to return all properties for an interface inheritance hierarchy), but I can't simply flatten the interfaces, because then I wouldn't know who is hiding who.
I know that probably this problem is solved somewhere in the Microsoft.CSharp.RuntimeBinder namespace (declared in the Microsoft.CSharp assembly). This because I'm trying to use C# rules and member lookup is necessary when you have dynamic method invocation, but I haven't been able to find anything (and then what I would get would be an Expression or perhaps a direct invocation).
After some thought it's clear that there is something similar in the Microsoft.VisualBasic assembly. VB.NET supports late binding. It's in Microsoft.VisualBasic.CompilerServices.NewLateBinding, but it doesn't expose the late bounded methods.

(note: shadowing = hiding = new in method/property/event definition in C#)
No one responded, so I'll post the code I cooked in the meantime. I hate to post 400 lines of code, but I wanted to be complete. There are two main methods: GetVisibleMethods and GetVisibleProperties. They are extension methods of the Type class. They will return the public visible (non-shadowed/non-overridden) methods/properties of a type. They should even handle VB.NET assemblies (VB.NET normally uses hide-by-name shadowing instead of hidebysig as done by C#). They cache their result in two static collections (Methods and Properties). The code is for C# 4.0, so I'm using ConcurrentDictionary<T, U>. If you are using C# 3.5 you can replace it with a Dictionary<T, U> but you have to protect it with a lock () { } when you read from it and when you write to it.
How does it works? It works by recursion (I know that recursion is normally bad, but I hope no one will create a 1.000 level inheritance chain).
For "real" types (non-interfaces) it walks upward one level (using recursion, so this one level up could go one level up and so on) and, from the returned list of methods/properties, it removes the methods/properties it's overloading/hiding.
For interfaces it's a little more complex. Type.GetInterfaces() returns all the interfaces that are inherited, ignoring if they are directly inherited or indirectly inherited. For each of those interfaces a list of declared methods/properties is calculated (through recursion). This list is paired with a list of methods/properties that are hidden by the interface (the HashSet<MethodInfo>/HashSet<PropertyInfo>). These methods/properties hidden by one interface or another are removed from all the other methods/properties returned from interfaces (so that if you have I1 with Method1(int), I2 inheriting from I1 that redeclares Method1(int) and in doing so hides I1.Method1 and I3 inheriting from I1 and I2, the fact that I2 hides I1.Method1 will be applied to the methods returned from exploring I1, so removing I1.Method1(int) (this happens because I don't generate an inheritance map for interfaces, I simply look at what hides what)).
From the returned collections of methods/properties one can use Linq to find the looked for method/property. Note that with interfaces you could find more than one method/property with a given signature. An example:
interface I1
{
void Method1();
}
interface I2
{
void Method1();
}
interface I3 : I1, I2
{
}
I3 will return two Method1().
The code:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class TypeEx
{
/// <summary>
/// Type, Tuple<Methods of type, (for interfaces)methods of base interfaces shadowed>
/// </summary>
public static readonly ConcurrentDictionary<Type, Tuple<MethodInfo[], HashSet<MethodInfo>>> Methods = new ConcurrentDictionary<Type, Tuple<MethodInfo[], HashSet<MethodInfo>>>();
/// <summary>
/// Type, Tuple<Properties of type, (for interfaces)properties of base interfaces shadowed>
/// </summary>
public static readonly ConcurrentDictionary<Type, Tuple<PropertyInfo[], HashSet<PropertyInfo>>> Properties = new ConcurrentDictionary<Type, Tuple<PropertyInfo[], HashSet<PropertyInfo>>>();
public static MethodInfo[] GetVisibleMethods(this Type type)
{
if (type.IsInterface)
{
return (MethodInfo[])type.GetVisibleMethodsInterfaceImpl().Item1.Clone();
}
return (MethodInfo[])type.GetVisibleMethodsImpl().Clone();
}
public static PropertyInfo[] GetVisibleProperties(this Type type)
{
if (type.IsInterface)
{
return (PropertyInfo[])type.GetVisiblePropertiesInterfaceImpl().Item1.Clone();
}
return (PropertyInfo[])type.GetVisiblePropertiesImpl().Clone();
}
private static MethodInfo[] GetVisibleMethodsImpl(this Type type)
{
Tuple<MethodInfo[], HashSet<MethodInfo>> tuple;
if (Methods.TryGetValue(type, out tuple))
{
return tuple.Item1;
}
var methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
if (type.BaseType == null)
{
Methods.TryAdd(type, Tuple.Create(methods, (HashSet<MethodInfo>)null));
return methods;
}
var baseMethods = type.BaseType.GetVisibleMethodsImpl().ToList();
foreach (var method in methods)
{
if (method.IsHideByName())
{
baseMethods.RemoveAll(p => p.Name == method.Name);
}
else
{
int numGenericArguments = method.GetGenericArguments().Length;
var parameters = method.GetParameters();
baseMethods.RemoveAll(p =>
{
if (!method.EqualSignature(numGenericArguments, parameters, p))
{
return false;
}
return true;
});
}
}
if (baseMethods.Count == 0)
{
Methods.TryAdd(type, Tuple.Create(methods, (HashSet<MethodInfo>)null));
return methods;
}
var methods3 = new MethodInfo[methods.Length + baseMethods.Count];
Array.Copy(methods, 0, methods3, 0, methods.Length);
baseMethods.CopyTo(methods3, methods.Length);
Methods.TryAdd(type, Tuple.Create(methods3, (HashSet<MethodInfo>)null));
return methods3;
}
private static Tuple<MethodInfo[], HashSet<MethodInfo>> GetVisibleMethodsInterfaceImpl(this Type type)
{
Tuple<MethodInfo[], HashSet<MethodInfo>> tuple;
if (Methods.TryGetValue(type, out tuple))
{
return tuple;
}
var methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
var baseInterfaces = type.GetInterfaces();
if (baseInterfaces.Length == 0)
{
tuple = Tuple.Create(methods, new HashSet<MethodInfo>());
Methods.TryAdd(type, tuple);
return tuple;
}
var baseMethods = new List<MethodInfo>();
var baseMethodsTemp = new MethodInfo[baseInterfaces.Length][];
var shadowedMethods = new HashSet<MethodInfo>();
for (int i = 0; i < baseInterfaces.Length; i++)
{
var tuple2 = baseInterfaces[i].GetVisibleMethodsInterfaceImpl();
baseMethodsTemp[i] = tuple2.Item1;
shadowedMethods.UnionWith(tuple2.Item2);
}
for (int i = 0; i < baseInterfaces.Length; i++)
{
baseMethods.AddRange(baseMethodsTemp[i].Where(p => !shadowedMethods.Contains(p)));
}
foreach (var method in methods)
{
if (method.IsHideByName())
{
baseMethods.RemoveAll(p =>
{
if (p.Name == method.Name)
{
shadowedMethods.Add(p);
return true;
}
return false;
});
}
else
{
int numGenericArguments = method.GetGenericArguments().Length;
var parameters = method.GetParameters();
baseMethods.RemoveAll(p =>
{
if (!method.EqualSignature(numGenericArguments, parameters, p))
{
return false;
}
shadowedMethods.Add(p);
return true;
});
}
}
if (baseMethods.Count == 0)
{
tuple = Tuple.Create(methods, shadowedMethods);
Methods.TryAdd(type, tuple);
return tuple;
}
var methods3 = new MethodInfo[methods.Length + baseMethods.Count];
Array.Copy(methods, 0, methods3, 0, methods.Length);
baseMethods.CopyTo(methods3, methods.Length);
tuple = Tuple.Create(methods3, shadowedMethods);
Methods.TryAdd(type, tuple);
return tuple;
}
private static PropertyInfo[] GetVisiblePropertiesImpl(this Type type)
{
Tuple<PropertyInfo[], HashSet<PropertyInfo>> tuple;
if (Properties.TryGetValue(type, out tuple))
{
return tuple.Item1;
}
var properties = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
if (type.BaseType == null)
{
Properties.TryAdd(type, Tuple.Create(properties, (HashSet<PropertyInfo>)null));
return properties;
}
var baseProperties = type.BaseType.GetVisiblePropertiesImpl().ToList();
foreach (var property in properties)
{
if (property.IsHideByName())
{
baseProperties.RemoveAll(p => p.Name == property.Name);
}
else
{
var indexers = property.GetIndexParameters();
baseProperties.RemoveAll(p =>
{
if (!property.EqualSignature(indexers, p))
{
return false;
}
return true;
});
}
}
if (baseProperties.Count == 0)
{
Properties.TryAdd(type, Tuple.Create(properties, (HashSet<PropertyInfo>)null));
return properties;
}
var properties3 = new PropertyInfo[properties.Length + baseProperties.Count];
Array.Copy(properties, 0, properties3, 0, properties.Length);
baseProperties.CopyTo(properties3, properties.Length);
Properties.TryAdd(type, Tuple.Create(properties3, (HashSet<PropertyInfo>)null));
return properties3;
}
private static Tuple<PropertyInfo[], HashSet<PropertyInfo>> GetVisiblePropertiesInterfaceImpl(this Type type)
{
Tuple<PropertyInfo[], HashSet<PropertyInfo>> tuple;
if (Properties.TryGetValue(type, out tuple))
{
return tuple;
}
var properties = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
var baseInterfaces = type.GetInterfaces();
if (baseInterfaces.Length == 0)
{
tuple = Tuple.Create(properties, new HashSet<PropertyInfo>());
Properties.TryAdd(type, tuple);
return tuple;
}
var baseProperties = new List<PropertyInfo>();
var basePropertiesTemp = new PropertyInfo[baseInterfaces.Length][];
var shadowedProperties = new HashSet<PropertyInfo>();
for (int i = 0; i < baseInterfaces.Length; i++)
{
var tuple2 = baseInterfaces[i].GetVisiblePropertiesInterfaceImpl();
basePropertiesTemp[i] = tuple2.Item1;
shadowedProperties.UnionWith(tuple2.Item2);
}
for (int i = 0; i < baseInterfaces.Length; i++)
{
baseProperties.AddRange(basePropertiesTemp[i].Where(p => !shadowedProperties.Contains(p)));
}
foreach (var property in properties)
{
if (property.IsHideByName())
{
baseProperties.RemoveAll(p =>
{
if (p.Name == property.Name)
{
shadowedProperties.Add(p);
return true;
}
return false;
});
}
else
{
var indexers = property.GetIndexParameters();
baseProperties.RemoveAll(p =>
{
if (!property.EqualSignature(indexers, p))
{
return false;
}
shadowedProperties.Add(p);
return true;
});
}
}
if (baseProperties.Count == 0)
{
tuple = Tuple.Create(properties, shadowedProperties);
Properties.TryAdd(type, tuple);
return tuple;
}
var properties3 = new PropertyInfo[properties.Length + baseProperties.Count];
Array.Copy(properties, 0, properties3, 0, properties.Length);
baseProperties.CopyTo(properties3, properties.Length);
tuple = Tuple.Create(properties3, shadowedProperties);
Properties.TryAdd(type, tuple);
return tuple;
}
private static bool EqualSignature(this MethodInfo method1, int numGenericArguments1, ParameterInfo[] parameters1, MethodInfo method2)
{
// To shadow by signature a method must have same name, same number of
// generic arguments, same number of parameters and same parameters' type
if (method1.Name != method2.Name)
{
return false;
}
if (numGenericArguments1 != method2.GetGenericArguments().Length)
{
return false;
}
var parameters2 = method2.GetParameters();
if (!parameters1.EqualParameterTypes(parameters2))
{
return false;
}
return true;
}
private static bool EqualSignature(this PropertyInfo property1, ParameterInfo[] indexers1, PropertyInfo property2)
{
// To shadow by signature a property must have same name,
// same number of indexers and same indexers' type
if (property1.Name != property2.Name)
{
return false;
}
var parameters2 = property1.GetIndexParameters();
if (!indexers1.EqualParameterTypes(parameters2))
{
return false;
}
return true;
}
private static bool EqualParameterTypes(this ParameterInfo[] parameters1, ParameterInfo[] parameters2)
{
if (parameters1.Length != parameters2.Length)
{
return false;
}
for (int i = 0; i < parameters1.Length; i++)
{
if (parameters1[i].IsOut != parameters2[i].IsOut)
{
return false;
}
if (parameters1[i].ParameterType.IsGenericParameter)
{
if (!parameters2[i].ParameterType.IsGenericParameter)
{
return false;
}
if (parameters1[i].ParameterType.GenericParameterPosition != parameters2[i].ParameterType.GenericParameterPosition)
{
return false;
}
}
else if (parameters1[i].ParameterType != parameters2[i].ParameterType)
{
return false;
}
}
return true;
}
private static bool IsHideByName(this MethodInfo method)
{
if (!method.Attributes.HasFlag(MethodAttributes.HideBySig) && (!method.Attributes.HasFlag(MethodAttributes.Virtual) || method.Attributes.HasFlag(MethodAttributes.NewSlot)))
{
return true;
}
return false;
}
private static bool IsHideByName(this PropertyInfo property)
{
var get = property.GetGetMethod();
if (get != null && get.IsHideByName())
{
return true;
}
var set = property.GetSetMethod();
if (set != null && set.IsHideByName())
{
return true;
}
return false;
}
}

Use overloaded method with BindingFlags parameter.
GetProperties(BindingFlags.DeclaredOnly)

Related

How to get the interface Methodinfo, based on concrete implementation's MethodInfo?

I have an interface IClass:
public interface IClass
{
[MyAttribute]
void Hello();
[MyAttribute]
void Farewell();
}
And an implementation Class1:
public class Class1 : IClass
{
public void Hello() { Console.WriteLine("Hi there") };
void IClass.Farewell() { Console.WriteLine("Goodbye!") };
}
I have a handle on Class1's MethodInfo's for Hello() and IClass.Farewell() by means of interception, but I need to find the MethodInfo of the interface definition in order to discover the usage of the attribute MyAttribute; something like this:
MethodInfo mi = context.Descriptior.CurrentMethod;
MethodInfo imi = GetInterfaceMethodInfo(mi) // ???
var mas = GetCustomAttributes<MyAttribute>();
if (mas.Count > 0)
{
// Profit!
}
EDIT:
A point I may have failed to highlight properly: I'm getting the initial MethodInfo instance from an interceptor, so I'm trying to find not only the interface's method, but I need to determine if there even is an interface in play, and if so I need to find its method declaration that corresponds to the called method.
I have a workaround that covers my current situation. On the plus side: it works. The downside: It uses string-comparisons, which I find are inherently presumptive.
private bool HasAttribute(MethodInfo methodInfo)
{
var type = methodInfo.DeclaringType;
var interfaces = type.GetInterfaces();
foreach (var #interface in interfaces)
{
var iMethodInfo = #interface.GetMethods()
.SingleOrDefault(x =>
(
methodInfo.Name.EndsWith($".{#interface.Name}.{x.Name}") || methodInfo.Name.Equals(x.Name)
)
&& IsSignatureMatch(x, methodInfo)
);
if (iMethodInfo != null)
{
Console.WriteLine(iMethodInfo.Name);
if (iMethodInfo.GetCustomAttribute<MyAttribute>() != null)
{
return true;
}
}
}
return false;
}
private bool IsSignatureMatch(MethodInfo methodInfoA, MethodInfo methodInfoB)
{
if (methodInfoA.ReturnType != methodInfoB.ReturnType)
{
return false;
}
var a = methodInfoA.GetParameters().Select(x => x.ParameterType).ToList();
var b = methodInfoB.GetParameters().Select(x => x.ParameterType).ToList();
if (a.Count != b.Count)
{
return false;
}
for (var i = 0; i < a.Count; i++)
{
if (a[i] != b[i])
{
return false;
}
}
return true;
}

How can I create a generic method to compare two list of any type. The type may be a List of class as well

Following is a class
public class Attribute
{
public string Name { get; set; }
public string Value { get; set; }
}
Following is the code in my main method
{
var test = new List<Attribute>();
test.Add(new Attribute { Name = "Don", Value = "21" });
test.Add(new Attribute { Value = "34", Name = "Karthik" });
var test1 = new List<Attribute>();
test1.Add(new Attribute { Name = "Don", Value = "21" });
test1.Add(new Attribute { Value = "34", Name = "Karthik" });
var obj = new Program();
var areEqual1 = obj.CompareList<List<Attribute>>(test, test1);
}
I have a ComapreList method
public bool CompareList<T>(T firstList, T secondList) where T : class
{
var list1 = firstList as IList<T>;
return true;
}
Now, list1 has null. I know that .net does not allow us to do this. But is there any other way where I can cast this generic list. My purpose is to compare each property value of these two list. I am using reflection to get the property but it works only if I can convert the firstlist/secondlist to something enumerable. if I directly use the name of the class in the IList<> (firstList as IList<Attribute>) it works, but not if I give <T>. Please help.
Just create method parameterized by type of lists items type. Even more, you can create method which compares any type of collections:
public bool CompareSequences<T> (IEnumerable<T> first, IEnumerable<T> second,
Comparer<T> comparer = null)
{
comparer = comparer ?? Comparer<T>.Default;
if (first == null)
throw new ArgumentNullException(nameof(first));
if (second == null)
throw new ArgumentNullException(nameof(second));
var firstIterator = first.GetEnumerator();
var secondIterator = second.GetEnumerator();
while(true)
{
bool firstHasItem = firstIterator.MoveNext();
bool secondHasItem = secondIterator.MoveNext();
if (firstHasItem != secondHasItem)
return false;
if (!firstHasItem && !secondHasItem)
return true;
if (comparer.Compare(firstIterator.Current, secondIterator.Current) != 0)
return false;
}
}
If collection items are primitive types, you can use default comparer. But if collections contain custom items, you need either IComparable to be implemented by collection items type:
public class Attribute : IComparable<Attribute>
{
public string Name { get; set; }
public string Value { get; set; }
public int CompareTo (Attribute other)
{
int result = Name.CompareTo(other.Name);
if (result == 0)
return Value.CompareTo(other.Value);
return result;
}
}
Or you can create and pass comparer instance. You can create comparer which is using reflection to compare fields/properties of some type. But it's not as simple as you might think - properties can be complex type or collections.
Usage:
var areEqual1 = obj.CompareSequences(test, test1);
If you don't need to compare objects with complex structure (which have inner collections and other custom objects) then you can use comparer like this one:
public class SimplePropertiesComparer<T> : Comparer<T>
{
public override int Compare (T x, T y)
{
Type type = typeof(T);
var flags = BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance;
foreach (var property in type.GetProperties(flags))
{
var propertyType = property.PropertyType;
if (!typeof(IComparable).IsAssignableFrom(propertyType))
throw new NotSupportedException($"{propertyType} props are not supported.");
var propertyValueX = (IComparable)property.GetValue(x);
var propertyValueY = (IComparable)property.GetValue(y);
if (propertyValueX == null && propertyValueY == null)
continue;
if (propertyValueX == null)
return -1;
int result = propertyValueX.CompareTo(property.GetValue(y));
if (result == 0)
continue;
return result;
}
return 0;
}
}
And pass it to sequence comparer
var equal = obj.CompareSequences(test, test1, new SimplePropertiesComparer<Attribute>());
Change the signature of your method and remove the then redundant cast:
public bool CompareList<T>(IList<T> firstList, IList<T> secondList) where T : class
{
var list1 = firstList as IList<T>; // Cast is not necessary any more
return true;
}
public bool CompareGenericLists<T, U>(List<T> list1, List<U> list2)
{
try
{
if (typeof(T).Equals(typeof(U)))
{
//For checking null lists
if (list1 == null && list2 == null)
return true;
if (list1 == null || list2 == null)
throw new Exception("One of the Lists is Null");
if (list1.Count.Equals(list2.Count))
{
Type type = typeof(T);
//For primitive lists
if (type.IsPrimitive)
{
int flag = 0;
for (int i = 0; i < list1.Count; i++)
{
if (list1.ElementAt(i).Equals(list2.ElementAt(i)))
flag++;
}
if (flag != list1.Count)
throw new Exception("Objects values are not same");
}
//For Reference List
else
{
for (int i = 0; i < list1.Count; i++)
{
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
string Object1Value = string.Empty;
string Object2Value = string.Empty;
Object1Value = type.GetProperty(property.Name).GetValue(list1.ElementAt(i)).ToString();
Object2Value = type.GetProperty(property.Name).GetValue(list2.ElementAt(i)).ToString();
if (Object1Value != Object2Value)
{
throw new Exception("Objects values are not same");
}
}
}
}
}
else
throw new Exception("Length of lists is not Same");
}
else
throw new Exception("Different type of lists");
}
catch(Exception ex)
{
throw ex;
}
return true;
}
this method can be used for both primitive and reference lists.try this method.It will compare type,counts,and members of lists.

How to get the Count property using reflection for Generic types

I have a list of objects, of which I cannot know the type of at compile-time.
I need to identify any of these objects where a 'Count' property exists, and get the value if it does.
This code works for simple Collection types:
PropertyInfo countProperty = objectValue.GetType().GetProperty("Count");
if (countProperty != null)
{
int count = (int)countProperty.GetValue(objectValue, null);
}
The problem is that this doesn't work for generic types, such as IDictionary<TKey,TValue>. In those cases, the 'countProperty' value is returned as null, even though a 'Count' property exists in the instanced object.
All I want to do is identify any collection/dictionary based object and find the size of it, if it has one.
Edit: as requested, here's the entire listing of code that doesn't work
private static void GetCacheCollectionValues(ref CacheItemInfo item, object cacheItemValue)
{
try
{
//look for a count property using reflection
PropertyInfo countProperty = cacheItemValue.GetType().GetProperty("Count");
if (countProperty != null)
{
int count = (int)countProperty.GetValue(cacheItemValue, null);
item.Count = count;
}
else
{
//poke around for a 'values' property
PropertyInfo valuesProperty = cacheItemValue.GetType().GetProperty("Values");
int valuesCount = -1;
if (valuesProperty != null)
{
object values = valuesProperty.GetValue(cacheItemValue, null);
if (values != null)
{
PropertyInfo valuesCountProperty = values.GetType().GetProperty("Count");
if (countProperty != null)
{
valuesCount = (int)valuesCountProperty.GetValue(cacheItemValue, null);
}
}
}
if (valuesCount > -1)
item.Count = valuesCount;
else
item.Count = -1;
}
}
catch (Exception ex)
{
item.Count = -1;
item.Message = "Exception on 'Count':" + ex.Message;
}
}
This works OK on simple collections, but not on an object created from a class I have which is derived from Dictionary<TKey,TValue>. Ie
CustomClass :
Dictionary<TKey,TValue>
CacheItemInfo is just a simple class that contains properties for cache items - ie, key, count, type, expiration datetime
The first thing you should try is casting to ICollection, as this has a very cheap .Count:
ICollection col = objectValue as ICollection;
if(col != null) return col.Count;
The Count for dictionary should work though - I've tested this with Dictionary<,> and it works fine - but note that even if something implements IDictionary<,>, the concrete type (returned via GetType()) doesn't have to have a .Count on the public API - it could use explicit interface implementation to satisfy the interface while not having a public int Count {get;}. Like I say: it works for Dictionary<,> - but not necessarily for every type.
As a last ditch effort if everything else fails:
IEnumerable enumerable = objectValue as IEnumerable;
if(enumerable != null)
{
int count = 0;
foreach(object val in enumerable) count++;
return count;
}
Edit to look into the Dictionary<,> question raised in comments:
using System;
using System.Collections;
using System.Collections.Generic;
public class CustomClass : Dictionary<int, int> { }
public class CacheItemInfo
{
public int Count { get; set; }
public string Message { get; set; }
}
class Program {
public static void Main() {
var cii = new CacheItemInfo();
var data = new CustomClass { { 1, 1 }, { 2, 2 }, { 3, 3 } };
GetCacheCollectionValues(ref cii, data);
Console.WriteLine(cii.Count); // expect 3
}
private static void GetCacheCollectionValues(ref CacheItemInfo item, object cacheItemValue)
{
try
{
ICollection col;
IEnumerable enumerable;
if (cacheItemValue == null)
{
item.Count = -1;
}
else if ((col = cacheItemValue as ICollection) != null)
{
item.Count = col.Count;
}
else if ((enumerable = cacheItemValue as IEnumerable) != null)
{
int count = 0;
foreach (object val in enumerable) count++;
item.Count = count;
}
else
{
item.Count = -1;
}
}
catch (Exception ex)
{
item.Count = -1;
item.Message = "Exception on 'Count':" + ex.Message;
}
}
}
How about adding this after your first check (!untested!) ...
foreach (Type interfaceType in objectValue.GetType().GetInterfaces())
{
countProperty = interfaceType.GetProperty("Count");
//etc.
}

Comparing object properties in c# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 4 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
This is what I've come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.
Now, this does work - but in the interest of improving the quality of my code I thought I'd throw it out for scrutiny. How can it be better/more efficient/etc.?
/// <summary>
/// Compare property values (as strings)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool PropertiesEqual(object comparisonObject)
{
Type sourceType = this.GetType();
Type destinationType = comparisonObject.GetType();
if (sourceType == destinationType)
{
PropertyInfo[] sourceProperties = sourceType.GetProperties();
foreach (PropertyInfo pi in sourceProperties)
{
if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
{
// if both are null, don't try to compare (throws exception)
}
else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
{
// only need one property to be different to fail Equals.
return false;
}
}
}
else
{
throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");
}
return true;
}
I was looking for a snippet of code that would do something similar to help with writing unit test. Here is what I ended up using.
public static bool PublicInstancePropertiesEqual<T>(T self, T to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
Type type = typeof(T);
List<string> ignoreList = new List<string>(ignore);
foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (!ignoreList.Contains(pi.Name))
{
object selfValue = type.GetProperty(pi.Name).GetValue(self, null);
object toValue = type.GetProperty(pi.Name).GetValue(to, null);
if (selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)))
{
return false;
}
}
}
return true;
}
return self == to;
}
EDIT:
Same code as above but uses LINQ and Extension methods :
public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
var type = typeof(T);
var ignoreList = new List<string>(ignore);
var unequalProperties =
from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !ignoreList.Contains(pi.Name) && pi.GetUnderlyingType().IsSimpleType() && pi.GetIndexParameters().Length == 0
let selfValue = type.GetProperty(pi.Name).GetValue(self, null)
let toValue = type.GetProperty(pi.Name).GetValue(to, null)
where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
select selfValue;
return !unequalProperties.Any();
}
return self == to;
}
public static class TypeExtensions
{
/// <summary>
/// Determine whether a type is simple (String, Decimal, DateTime, etc)
/// or complex (i.e. custom class with public properties and methods).
/// </summary>
/// <see cref="http://stackoverflow.com/questions/2442534/how-to-test-if-type-is-primitive"/>
public static bool IsSimpleType(
this Type type)
{
return
type.IsValueType ||
type.IsPrimitive ||
new[]
{
typeof(String),
typeof(Decimal),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(Guid)
}.Contains(type) ||
(Convert.GetTypeCode(type) != TypeCode.Object);
}
public static Type GetUnderlyingType(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Method:
return ((MethodInfo)member).ReturnType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
default:
throw new ArgumentException
(
"Input MemberInfo must be if type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"
);
}
}
}
UPDATE: The latest version of Compare-Net-Objects is located on GitHub , has NuGet package and Tutorial. It can be called like
//This is the comparison class
CompareLogic compareLogic = new CompareLogic();
ComparisonResult result = compareLogic.Compare(person1, person2);
//These will be different, write out the differences
if (!result.AreEqual)
Console.WriteLine(result.DifferencesString);
Or if you need to change some configuration, use
CompareLogic basicComparison = new CompareLogic()
{ Config = new ComparisonConfig()
{ MaxDifferences = propertyCount
//add other configurations
}
};
Full list of configurable parameters is in ComparisonConfig.cs
Original answer:
The limitations I see in your code:
The biggest one is that it doesn't do a deep object comparison.
It doesn't do an element by element comparison in case properties are lists or contain lists as elements (this can go n-levels).
It doesn't take into account that some type of properties should not be compared (e.g. a Func property used for filtering purposes, like the one in the PagedCollectionView class).
It doesn't keep track of what properties actually were different (so you can show in your assertions).
I was looking today for some solution for unit-testing purposes to do property by property deep comparison and I ended up using: http://comparenetobjects.codeplex.com.
It is a free library with just one class which you can simply use like this:
var compareObjects = new CompareObjects()
{
CompareChildren = true, //this turns deep compare one, otherwise it's shallow
CompareFields = false,
CompareReadOnly = true,
ComparePrivateFields = false,
ComparePrivateProperties = false,
CompareProperties = true,
MaxDifferences = 1,
ElementsToIgnore = new List<string>() { "Filter" }
};
Assert.IsTrue(
compareObjects.Compare(objectA, objectB),
compareObjects.DifferencesString
);
Also, it can be easily re-compiled for Silverlight. Just copy the one class into a Silverlight project and remove one or two lines of code for comparisons that are not available in Silverlight, like private members comparison.
I think it would be best to follow the pattern for Override Object#Equals()
For a better description: Read Bill Wagner's Effective C# - Item 9 I think
public override Equals(object obOther)
{
if (null == obOther)
return false;
if (object.ReferenceEquals(this, obOther)
return true;
if (this.GetType() != obOther.GetType())
return false;
# private method to compare members.
return CompareMembers(this, obOther as ThisClass);
}
Also in methods that check for equality, you should return either true or false. either they are equal or they are not.. instead of throwing an exception, return false.
I'd consider overriding Object#Equals.
Even though you must have considered this, using Reflection to compare properties is supposedly slow (I dont have numbers to back this up). This is the default behavior for valueType#Equals in C# and it is recommended that you override Equals for value types and do a member wise compare for performance. (Earlier I speed-read this as you have a collection of custom Property objects... my bad.)
Update-Dec 2011:
Of course, if the type already has a production Equals() then you need another approach.
If you're using this to compare immutable data structures exclusively for test purposes, you shouldn't add an Equals to production classes (Someone might hose the tests by chainging the Equals implementation or you may prevent creation of a production-required Equals implementation).
If performance doesn't matter, you could serialize them and compare the results:
var serializer = new XmlSerializer(typeof(TheObjectType));
StringWriter serialized1 = new StringWriter(), serialized2 = new StringWriter();
serializer.Serialize(serialized1, obj1);
serializer.Serialize(serialized2, obj2);
bool areEqual = serialized1.ToString() == serialized2.ToString();
I think the answer of Big T was quite good but the deep comparison was missing, so I tweaked it a little bit:
using System.Collections.Generic;
using System.Reflection;
/// <summary>Comparison class.</summary>
public static class Compare
{
/// <summary>Compare the public instance properties. Uses deep comparison.</summary>
/// <param name="self">The reference object.</param>
/// <param name="to">The object to compare.</param>
/// <param name="ignore">Ignore property with name.</param>
/// <typeparam name="T">Type of objects.</typeparam>
/// <returns><see cref="bool">True</see> if both objects are equal, else <see cref="bool">false</see>.</returns>
public static bool PublicInstancePropertiesEqual<T>(T self, T to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
var type = self.GetType();
var ignoreList = new List<string>(ignore);
foreach (var pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (ignoreList.Contains(pi.Name))
{
continue;
}
var selfValue = type.GetProperty(pi.Name).GetValue(self, null);
var toValue = type.GetProperty(pi.Name).GetValue(to, null);
if (pi.PropertyType.IsClass && !pi.PropertyType.Module.ScopeName.Equals("CommonLanguageRuntimeLibrary"))
{
// Check of "CommonLanguageRuntimeLibrary" is needed because string is also a class
if (PublicInstancePropertiesEqual(selfValue, toValue, ignore))
{
continue;
}
return false;
}
if (selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)))
{
return false;
}
}
return true;
}
return self == to;
}
}
I would add the following line to the PublicInstancePropertiesEqual method to avoid copy & paste errors:
Assert.AreNotSame(self, to);
Do you override .ToString() on all of your objects that are in the properties? Otherwise, that second comparison could come back with null.
Also, in that second comparison, I'm on the fence about the construct of !( A == B) compared to (A != B), in terms of readability six months/two years from now. The line itself is pretty wide, which is ok if you've got a wide monitor, but might not print out very well. (nitpick)
Are all of your objects always using properties such that this code will work? Could there be some internal, non-propertied data that could be different from one object to another, but all exposed data is the same? I'm thinking of some data which could change over time, like two random number generators that happen to hit the same number at one point, but are going to produce two different sequences of information, or just any data that doesn't get exposed through the property interface.
If you are only comparing objects of the same type or further down the inheritance chain, why not specify the parameter as your base type, rather than object ?
Also do null checks on the parameter as well.
Furthermore I'd make use of 'var' just to make the code more readable (if its c#3 code)
Also, if the object has reference types as properties then you are just calling ToString() on them which doesn't really compare values. If ToString isn't overwridden then its just going to return the type name as a string which could return false-positives.
The first thing I would suggest would be to split up the actual comparison so that it's a bit more readable (I've also taken out the ToString() - is that needed?):
else {
object originalProperty = sourceType.GetProperty(pi.Name).GetValue(this, null);
object comparisonProperty = destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null);
if (originalProperty != comparisonProperty)
return false;
The next suggestion would be to minimise the use of reflection as much as possible - it's really slow. I mean, really slow. If you are going to do this, I would suggest caching the property references. I'm not intimately familiar with the Reflection API, so if this is a bit off, just adjust to make it compile:
// elsewhere
Dictionary<object, Property[]> lookupDictionary = new Dictionary<object, Property[]>;
Property[] objectProperties = null;
if (lookupDictionary.ContainsKey(sourceType)) {
objectProperties = lookupProperties[sourceType];
} else {
// build array of Property references
PropertyInfo[] sourcePropertyInfos = sourceType.GetProperties();
Property[] sourceProperties = new Property[sourcePropertyInfos.length];
for (int i=0; i < sourcePropertyInfos.length; i++) {
sourceProperties[i] = sourceType.GetProperty(pi.Name);
}
// add to cache
objectProperties = sourceProperties;
lookupDictionary[object] = sourceProperties;
}
// loop through and compare against the instances
However, I have to say that I agree with the other posters. This smells lazy and inefficient. You should be implementing IComparable instead :-).
here is revised one to treat null = null as equal
private bool PublicInstancePropertiesEqual<T>(T self, T to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
Type type = typeof(T);
List<string> ignoreList = new List<string>(ignore);
foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!ignoreList.Contains(pi.Name))
{
object selfValue = type.GetProperty(pi.Name).GetValue(self, null);
object toValue = type.GetProperty(pi.Name).GetValue(to, null);
if (selfValue != null)
{
if (!selfValue.Equals(toValue))
return false;
}
else if (toValue != null)
return false;
}
}
return true;
}
return self == to;
}
I ended up doing this:
public static string ToStringNullSafe(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
public static bool Compare<T>(T a, T b)
{
int count = a.GetType().GetProperties().Count();
string aa, bb;
for (int i = 0; i < count; i++)
{
aa = a.GetType().GetProperties()[i].GetValue(a, null).ToStringNullSafe();
bb = b.GetType().GetProperties()[i].GetValue(b, null).ToStringNullSafe();
if (aa != bb)
{
return false;
}
}
return true;
}
Usage:
if (Compare<ObjectType>(a, b))
Update
If you want to ignore some properties by name:
public static string ToStringNullSafe(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
public static bool Compare<T>(T a, T b, params string[] ignore)
{
int count = a.GetType().GetProperties().Count();
string aa, bb;
for (int i = 0; i < count; i++)
{
aa = a.GetType().GetProperties()[i].GetValue(a, null).ToStringNullSafe();
bb = b.GetType().GetProperties()[i].GetValue(b, null).ToStringNullSafe();
if (aa != bb && ignore.Where(x => x == a.GetType().GetProperties()[i].Name).Count() == 0)
{
return false;
}
}
return true;
}
Usage:
if (MyFunction.Compare<ObjType>(a, b, "Id","AnotherProp"))
You can optimize your code by calling GetProperties only once per type:
public static string ToStringNullSafe(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
public static bool Compare<T>(T a, T b, params string[] ignore)
{
var aProps = a.GetType().GetProperties();
var bProps = b.GetType().GetProperties();
int count = aProps.Count();
string aa, bb;
for (int i = 0; i < count; i++)
{
aa = aProps[i].GetValue(a, null).ToStringNullSafe();
bb = bProps[i].GetValue(b, null).ToStringNullSafe();
if (aa != bb && ignore.Where(x => x == aProps[i].Name).Count() == 0)
{
return false;
}
}
return true;
}
For completeness I want to add reference to
http://www.cyotek.com/blog/comparing-the-properties-of-two-objects-via-reflection
It has more complete logic than most of others answers on this page.
However I prefer Compare-Net-Objects library
https://github.com/GregFinzer/Compare-Net-Objects (referred by Liviu Trifoi's answer)
The library has NuGet package http://www.nuget.org/packages/CompareNETObjects and multiple options to configure.
Make sure objects aren't null.
Having obj1 and obj2:
if(obj1 == null )
{
return false;
}
return obj1.Equals( obj2 );
This works even if the objects are different. you could customize the methods in the utilities class maybe you want to compare private properties as well...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class ObjectA
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
public DateTime PropertyD { get; set; }
public string FieldA;
public DateTime FieldB;
}
class ObjectB
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
public DateTime PropertyD { get; set; }
public string FieldA;
public DateTime FieldB;
}
class Program
{
static void Main(string[] args)
{
// create two objects with same properties
ObjectA a = new ObjectA() { PropertyA = "test", PropertyB = "test2", PropertyC = "test3" };
ObjectB b = new ObjectB() { PropertyA = "test", PropertyB = "test2", PropertyC = "test3" };
// add fields to those objects
a.FieldA = "hello";
b.FieldA = "Something differnt";
if (a.ComparePropertiesTo(b))
{
Console.WriteLine("objects have the same properties");
}
else
{
Console.WriteLine("objects have diferent properties!");
}
if (a.CompareFieldsTo(b))
{
Console.WriteLine("objects have the same Fields");
}
else
{
Console.WriteLine("objects have diferent Fields!");
}
Console.Read();
}
}
public static class Utilities
{
public static bool ComparePropertiesTo(this Object a, Object b)
{
System.Reflection.PropertyInfo[] properties = a.GetType().GetProperties(); // get all the properties of object a
foreach (var property in properties)
{
var propertyName = property.Name;
var aValue = a.GetType().GetProperty(propertyName).GetValue(a, null);
object bValue;
try // try to get the same property from object b. maybe that property does
// not exist!
{
bValue = b.GetType().GetProperty(propertyName).GetValue(b, null);
}
catch
{
return false;
}
if (aValue == null && bValue == null)
continue;
if (aValue == null && bValue != null)
return false;
if (aValue != null && bValue == null)
return false;
// if properties do not match return false
if (aValue.GetHashCode() != bValue.GetHashCode())
{
return false;
}
}
return true;
}
public static bool CompareFieldsTo(this Object a, Object b)
{
System.Reflection.FieldInfo[] fields = a.GetType().GetFields(); // get all the properties of object a
foreach (var field in fields)
{
var fieldName = field.Name;
var aValue = a.GetType().GetField(fieldName).GetValue(a);
object bValue;
try // try to get the same property from object b. maybe that property does
// not exist!
{
bValue = b.GetType().GetField(fieldName).GetValue(b);
}
catch
{
return false;
}
if (aValue == null && bValue == null)
continue;
if (aValue == null && bValue != null)
return false;
if (aValue != null && bValue == null)
return false;
// if properties do not match return false
if (aValue.GetHashCode() != bValue.GetHashCode())
{
return false;
}
}
return true;
}
}
Update on Liviu's answer above - CompareObjects.DifferencesString has been deprecated.
This works well in a unit test:
CompareLogic compareLogic = new CompareLogic();
ComparisonResult result = compareLogic.Compare(object1, object2);
Assert.IsTrue(result.AreEqual);
This method will get properties of the class and compare the values for each property. If any of the values are different, it will return false, else it will return true.
public static bool Compare<T>(T Object1, T object2)
{
//Get the type of the object
Type type = typeof(T);
//return false if any of the object is false
if (Object1 == null || object2 == null)
return false;
//Loop through each properties inside class and get values for the property from both the objects and compare
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
if (property.Name != "ExtensionData")
{
string Object1Value = string.Empty;
string Object2Value = string.Empty;
if (type.GetProperty(property.Name).GetValue(Object1, null) != null)
Object1Value = type.GetProperty(property.Name).GetValue(Object1, null).ToString();
if (type.GetProperty(property.Name).GetValue(object2, null) != null)
Object2Value = type.GetProperty(property.Name).GetValue(object2, null).ToString();
if (Object1Value.Trim() != Object2Value.Trim())
{
return false;
}
}
}
return true;
}
Usage:
bool isEqual = Compare<Employee>(Object1, Object2)
To expand on #nawfal:s answer, I use this to test objects of different types in my unit tests to compare equal property names. In my case database entity and DTO.
Used like this in my test;
Assert.IsTrue(resultDto.PublicInstancePropertiesEqual(expectedEntity));
public static bool PublicInstancePropertiesEqual<T, Z>(this T self, Z to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
var type = typeof(T);
var type2 = typeof(Z);
var ignoreList = new List<string>(ignore);
var unequalProperties =
from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !ignoreList.Contains(pi.Name)
let selfValue = type.GetProperty(pi.Name).GetValue(self, null)
let toValue = type2.GetProperty(pi.Name).GetValue(to, null)
where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
select selfValue;
return !unequalProperties.Any();
}
return self == null && to == null;
}
sometimes you don't want to compare all public properties and want to compare only the subset of them, so in this case you can just move logic to compare the desired list of properties to abstract class
public abstract class ValueObject<T> where T : ValueObject<T>
{
protected abstract IEnumerable<object> GetAttributesToIncludeInEqualityCheck();
public override bool Equals(object other)
{
return Equals(other as T);
}
public bool Equals(T other)
{
if (other == null)
{
return false;
}
return GetAttributesToIncludeInEqualityCheck()
.SequenceEqual(other.GetAttributesToIncludeInEqualityCheck());
}
public static bool operator ==(ValueObject<T> left, ValueObject<T> right)
{
return Equals(left, right);
}
public static bool operator !=(ValueObject<T> left, ValueObject<T> right)
{
return !(left == right);
}
public override int GetHashCode()
{
int hash = 17;
foreach (var obj in this.GetAttributesToIncludeInEqualityCheck())
hash = hash * 31 + (obj == null ? 0 : obj.GetHashCode());
return hash;
}
}
and use this abstract class later to compare the objects
public class Meters : ValueObject<Meters>
{
...
protected decimal DistanceInMeters { get; private set; }
...
protected override IEnumerable<object> GetAttributesToIncludeInEqualityCheck()
{
return new List<Object> { DistanceInMeters };
}
}
my solution inspired from Aras Alenin answer above where I added one level of object comparison and a custom object for comparison results. I am also interested to get property name with object name:
public static IEnumerable<ObjectPropertyChanged> GetPublicSimplePropertiesChanged<T>(this T previous, T proposedChange,
string[] namesOfPropertiesToBeIgnored) where T : class
{
return GetPublicGenericPropertiesChanged(previous, proposedChange, namesOfPropertiesToBeIgnored, true, null, null);
}
public static IReadOnlyList<ObjectPropertyChanged> GetPublicGenericPropertiesChanged<T>(this T previous, T proposedChange,
string[] namesOfPropertiesToBeIgnored) where T : class
{
return GetPublicGenericPropertiesChanged(previous, proposedChange, namesOfPropertiesToBeIgnored, false, null, null);
}
/// <summary>
/// Gets the names of the public properties which values differs between first and second objects.
/// Considers 'simple' properties AND for complex properties without index, get the simple properties of the children objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="previous">The previous object.</param>
/// <param name="proposedChange">The second object which should be the new one.</param>
/// <param name="namesOfPropertiesToBeIgnored">The names of the properties to be ignored.</param>
/// <param name="simpleTypeOnly">if set to <c>true</c> consider simple types only.</param>
/// <param name="parentTypeString">The parent type string. Meant only for recursive call with simpleTypeOnly set to <c>true</c>.</param>
/// <param name="secondType">when calling recursively, the current type of T must be clearly defined here, as T will be more generic (using base class).</param>
/// <returns>
/// the names of the properties
/// </returns>
private static IReadOnlyList<ObjectPropertyChanged> GetPublicGenericPropertiesChanged<T>(this T previous, T proposedChange,
string[] namesOfPropertiesToBeIgnored, bool simpleTypeOnly, string parentTypeString, Type secondType) where T : class
{
List<ObjectPropertyChanged> propertiesChanged = new List<ObjectPropertyChanged>();
if (previous != null && proposedChange != null)
{
var type = secondType == null ? typeof(T) : secondType;
string typeStr = parentTypeString + type.Name + ".";
var ignoreList = namesOfPropertiesToBeIgnored.CreateList();
IEnumerable<IEnumerable<ObjectPropertyChanged>> genericPropertiesChanged =
from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !ignoreList.Contains(pi.Name) && pi.GetIndexParameters().Length == 0
&& (!simpleTypeOnly || simpleTypeOnly && pi.PropertyType.IsSimpleType())
let firstValue = type.GetProperty(pi.Name).GetValue(previous, null)
let secondValue = type.GetProperty(pi.Name).GetValue(proposedChange, null)
where firstValue != secondValue && (firstValue == null || !firstValue.Equals(secondValue))
let subPropertiesChanged = simpleTypeOnly || pi.PropertyType.IsSimpleType()
? null
: GetPublicGenericPropertiesChanged(firstValue, secondValue, namesOfPropertiesToBeIgnored, true, typeStr, pi.PropertyType)
let objectPropertiesChanged = subPropertiesChanged != null && subPropertiesChanged.Count() > 0
? subPropertiesChanged
: (new ObjectPropertyChanged(proposedChange.ToString(), typeStr + pi.Name, firstValue.ToStringOrNull(), secondValue.ToStringOrNull())).CreateList()
select objectPropertiesChanged;
if (genericPropertiesChanged != null)
{ // get items from sub lists
genericPropertiesChanged.ForEach(a => propertiesChanged.AddRange(a));
}
}
return propertiesChanged;
}
Using the following class to store comparison results
[System.Serializable]
public class ObjectPropertyChanged
{
public ObjectPropertyChanged(string objectId, string propertyName, string previousValue, string changedValue)
{
ObjectId = objectId;
PropertyName = propertyName;
PreviousValue = previousValue;
ProposedChangedValue = changedValue;
}
public string ObjectId { get; set; }
public string PropertyName { get; set; }
public string PreviousValue { get; set; }
public string ProposedChangedValue { get; set; }
}
And a sample unit test:
[TestMethod()]
public void GetPublicGenericPropertiesChangedTest1()
{
// Define objects to test
Function func1 = new Function { Id = 1, Description = "func1" };
Function func2 = new Function { Id = 2, Description = "func2" };
FunctionAssignment funcAss1 = new FunctionAssignment
{
Function = func1,
Level = 1
};
FunctionAssignment funcAss2 = new FunctionAssignment
{
Function = func2,
Level = 2
};
// Main test: read properties changed
var propertiesChanged = Utils.GetPublicGenericPropertiesChanged(funcAss1, funcAss2, null);
Assert.IsNotNull(propertiesChanged);
Assert.IsTrue(propertiesChanged.Count == 3);
Assert.IsTrue(propertiesChanged[0].PropertyName == "FunctionAssignment.Function.Description");
Assert.IsTrue(propertiesChanged[1].PropertyName == "FunctionAssignment.Function.Id");
Assert.IsTrue(propertiesChanged[2].PropertyName == "FunctionAssignment.Level");
}

C# Reflection Indexed Properties

I am writing a Clone method using reflection. How do I detect that a property is an indexed property using reflection? For example:
public string[] Items
{
get;
set;
}
My method so far:
public static T Clone<T>(T from, List<string> propertiesToIgnore) where T : new()
{
T to = new T();
Type myType = from.GetType();
PropertyInfo[] myProperties = myType.GetProperties();
for (int i = 0; i < myProperties.Length; i++)
{
if (myProperties[i].CanWrite && !propertiesToIgnore.Contains(myProperties[i].Name))
{
myProperties[i].SetValue(to,myProperties[i].GetValue(from,null),null);
}
}
return to;
}
if (propertyInfo.GetIndexParameters().Length > 0)
{
// Property is an indexer
}
Sorry, but
public string[] Items { get; set; }
is not an indexed property, it's merely of an array type!
However the following is:
public string this[int index]
{
get { ... }
set { ... }
}
What you want is the GetIndexParameters() method. If the array that it returns has more than 0 items, that means it's an indexed property.
See the MSDN documentation for more details.
If you call property.GetValue(obj,null), and the property IS indexed, then you will get a parameter count mismatch exception. Better to check whether the property is indexed using GetIndexParameters() and then decide what to do.
Here is some code that worked for me:
foreach (PropertyInfo property in obj.GetType().GetProperties())
{
object value = property.GetValue(obj, null);
if (value is object[])
{
....
}
}
P.S. .GetIndexParameters().Length > 0) works for the case described in this article: http://msdn.microsoft.com/en-us/library/b05d59ty.aspx
So if you care about the property named Chars for a value of type string, use that, but it does not work for most of the arrays I was interested in, including, I am pretty sure, a string array from the original question.
You can convert the indexer to IEnumerable
public static IEnumerable<T> AsEnumerable<T>(this object o) where T : class {
var list = new List<T>();
System.Reflection.PropertyInfo indexerProperty = null;
foreach (System.Reflection.PropertyInfo pi in o.GetType().GetProperties()) {
if (pi.GetIndexParameters().Length > 0) {
indexerProperty = pi;
break;
}
}
if (indexerProperty.IsNotNull()) {
var len = o.GetPropertyValue<int>("Length");
for (int i = 0; i < len; i++) {
var item = indexerProperty.GetValue(o, new object[]{i});
if (item.IsNotNull()) {
var itemObject = item as T;
if (itemObject.IsNotNull()) {
list.Add(itemObject);
}
}
}
}
return list;
}
public static bool IsNotNull(this object o) {
return o != null;
}
public static T GetPropertyValue<T>(this object source, string property) {
if (source == null)
throw new ArgumentNullException("source");
var sourceType = source.GetType();
var sourceProperties = sourceType.GetProperties();
var properties = sourceProperties
.Where(s => s.Name.Equals(property));
if (properties.Count() == 0) {
sourceProperties = sourceType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);
properties = sourceProperties.Where(s => s.Name.Equals(property));
}
if (properties.Count() > 0) {
var propertyValue = properties
.Select(s => s.GetValue(source, null))
.FirstOrDefault();
return propertyValue != null ? (T)propertyValue : default(T);
}
return default(T);
}

Categories