Click here to Skip to main content
15,353,432 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have following simple interface
public interface IWrite {

void SaveToFile(string path);

public class A :IWrite {

[CustomSerialize('some value')]
public B B1 {get;set}

[CustomSerialize('some value')]
public C C1 {get;set}


public class B :IWrite{

public class C :IWrite{

I wrote following code to get a list of properties that has my custom attribute from class A

List<propertyinfo> result = this.GetType().GetProperties()
p =>
.GetCustomAttributes(typeof(CustomSerializeAttribute), false)
.Any(ca => ((CustomSerializeAttribute) ca).SerializeType == 'some value')

I know that every propertyInfo in the result list has interface implementation of IWrite

My question is , how actually I am invoking SaveToFile() method for each property in the result list

Means , I would like to invoke SaveToFile() on B1 and C1 objects

Thanks a lot,

What I have tried:

I tried

result.ForEach(x =>
MethodInfo m = x.PropertyType.GetMethod("SaveToFile");
m.Invoke(x.GetValue(this, null), new object[] { "path" });

But GetMethod returns always null

What I am doing wrong ??
Updated 23-Jun-19 15:11pm
lmoelleb 23-Jun-19 11:57am
Typically GetMethod returns null if the binding flags are not correct. But if you get the value of the property and you know it implements IWrite - why not just cast it to IWrite and call SaveToFile directly?

I do not understand why you think you need reflection here.

You can serialize an instance of 'A, and that will include the instances of 'B, 'C: public Properties with both 'get and 'set can be serialized: [^].
Instead of invoking the get method., why don't you just get the property's .Value?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900