Home > OS >  error "does not contain a definition for 'getProperty'" when trying to set prope
error "does not contain a definition for 'getProperty'" when trying to set prope

Time:02-26

void myFunc<M>()
{
    dynamic uploadReq = (M)Activator.CreateInstance(typeof(M));
    uploadReq.getProperty("Credentials").SetValue(null);
}

I have a function where I supply a type, an object of this type is created, and then a property on the object is set to null. I get an error

MyCustomType does not contain a definition for 'getProperty'

How can I fix this?

CodePudding user response:

GetProperty its method of Type. Object has no it. You can use this way:

  1. call GetProperty from type

  2. set value to object

    public static void  myFunc<M>()
     {
         dynamic uploadReq = (M)Activator.CreateInstance(typeof(M));
         typeof(M).GetProperty("Credentials").SetValue(uploadReq, null);
     }
    

CodePudding user response:

In this specific snippet of code you don't need dynamic or reflection, just use the generic version of the CreateInstance method or even better the constructor of the type. This is faster and also provides compile time checks.

void myFunc<M>() where M : new()
{
   M uploadReq = new M();
   uploadReq.Credentials = null;
}

or

M uploadReq = Activator.CreateInstance<M>();
uploadReq.Credentials = null;
  • Related