I have pretty simple piece of code
var propertyBuilder =
typeBuilder.DefineProperty(upperName, PropertyAttributes.None, propertyType, new[] { propertyType });
propertyBuilder.SetConstant(Convert.ChangeType(propertyInfo.Default, propertyType));
After that when I call CreateType() method and create an instance of the class I am trying to inspect value of the property with the default value assigned, but I cannot see any changes.
I cannot use SetValue method after I create an instance of the class, because all constructed types are stored inside metadata dictionary and can be used from different places in the code.
Any suggestions why SetConstant method is not working?
SetConstant()doesn’t do what you think it does. It sets a “default value” associated with the property, but that value is not actually used anywhere (though you can retrieve it usingGetConstantValue()).To actually return some constant value from the getter of the property, you will need to create the getter method and set its IL to return the value. But since you can’t store arbitrary types in the assembly itself, this will be hard to do generically. For example, if the property was
int, it would look like this:ldc.i4is an IL instruction to load a constant integer onto the IL stack. For other types, you would need different instructions.