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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With