Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if T object has a property and set property

Hello i am having a generic method

public async Task<T> MyMethod<T>(...)
{
 //logic here...
}

i would like inside this method to check if the T object has a specific property and then set a value to this property:

I've tried creating a dynamic object and do something like this:

var result = default(T);
dynamic obj = result;

Error error = new Error();
error.Message = "An error occured, please try again later.";
error.Name = "Error";

obj.Errors.Add(error);
result = obj;

return result;

But it doesnt seem to work.

like image 616
ChrisK Avatar asked Nov 18 '15 16:11

ChrisK


2 Answers

You should get a runtime type of the object with object.GetType, then you can check if it has a particular property with Type.GetProperty , and if yes, call PropertyInfo.SetValue :

PropertyInfo pi = obj.GetType().GetProperty("PropertyName");
if (pi != null)
{
    pi.SetValue(obj, value);
}
like image 65
w.b Avatar answered Nov 10 '22 01:11

w.b


If you control all the possible types which use MyMethod, the easiest option is to create an interface which defines the properties you need:

public interface IThing
{
    IList<Error> Errors { get; }
}

And change the method signature:

public async Task<T> MyMethod<T>(...) where T : IThing

If you do that, every item passed in will have to implement your interface and as a result have an Errors property.

like image 28
Trevor Pilley Avatar answered Nov 09 '22 23:11

Trevor Pilley