I need to assign values to properties through reflection, and it has been OK to every cases tested so far, except one with the type of System.Reflection.Missing. For example this is the class:
public class SomeClass
{
public System.Reflection.Missing MissingProp { get; set; }
}
And this is the code that assigns to the property through reflection:
var inst = new SomeClass();
var prop = typeof (SomeClass).GetProperty("MissingProp");
prop.SetValue(inst, Missing.Value, null);
And this is the exception I’m receiving:
System.ArgumentException: Missing parameter does not have a default value.
Parameter name: parameters
at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
at ClassesWithNoProperties.Program.Main(String[] args) in D:\Documents\Documents\Visual Studio 2010\Projects\C#\ClassesWithNoProperties\ClassesWithNoProperties\Program.cs:line 24
I have tested my library with too many cases that uses the same code for assigning values to properties, and this is the only case (System.Reflection.Missing) that I’m observing such a behaviour.
How do I achieve this kind of assignment in C#?
The error message is quite self-explanatory – the Missing.Value can only be used as a placeholder in methods that have optional parameters. What you’re trying to do, using it in a method to set the value of an instance using a PropertyInfo, simply doesn’t make sense, and Missing.Value knows this so it throws an exception.
Strangely, you could probably get this to work using VB.Net, as VB.Net supports default parameters. C# does not.