Reputation: 270
I have a class like -
class AClass {
public int P1 { get; set; }
public string P2 { get; set; }
public string P3 { get; set; }
}
Another class like -
class BClass {
public int P1 { get; set; }
public string P2{ get; set; }
}
I want to check check if class AClass
contains(should match both name and type) properties of BClass
or not. How can do that?
Upvotes: 0
Views: 727
Reputation: 481
You can use reflection on the types and find the properties with the same name & type
var commonProperties =
typeof(AClass).GetProperties().Join(typeof(BClass).GetProperties(),
prop => new {prop.PropertyType, prop.Name},
prop => new {prop.PropertyType, prop.Name},
(propA, propB)=>propA.Name);
Do note however, that code snippet only checks for Name & Type. There are dozens of other things that could be different, like availability of get, set, attributes,..
Upvotes: 1
Reputation: 10287
a way of testing this with reflection could be this:
var propertiesOfA = typeof(AClass).GetProperties();
var propertiesOfB = typeof(BClass).GetProperties();
var commonProperties = propertiesOfB.Where(
b => propertiesOfA.Any(
a =>
b.Name == a.Name
&& b.PropertyType == a.PropertyType
)
).ToArray();
Upvotes: 1
Reputation: 1131
You can check the properties of the two classes and select these names.
var duplicates = typeof(AClass).GetProperties().Where(a => typeof(BClass).GetProperties().Any(b => b.Name == a.Name && b.PropertyType == a.PropertyType)).Select(x => x.Name);
Upvotes: 0
Reputation: 728
You could solve tis using reflection :
PropertyInfo[] myPropertyInfo;
myPropertyInfo = Type.GetType("System.Type").GetProperties();
Console.WriteLine("Properties of System.Type are:");
for (int i = 0; i < myPropertyInfo.Length; i++)
{
Console.WriteLine(myPropertyInfo[i].ToString());
}
Read more at : https://learn.microsoft.com/en-US/dotnet/api/system.type.getproperties?view=netcore-3.1
Upvotes: 0