The following code does not seem to work, although according to documentation the part with boxing should work. I seem not be able to find more information on this than the article at Value Type Property setting
This question is also not similar as in Setting a property of a property in a struct? as this has nothing to do with reflection, which I am trying to use.
The code is just a small piece of a much larger project (using reflection to get something done) but demonstrates the issue.
The specialty in this example is that the property we want to set is in a value type (struct) and SetValue seems not to be handling this very well...
Imports System.Drawing
Module Module1
Sub Main()
Console.WriteLine("Starting test")
Dim s As Size
Console.WriteLine("Created size: {0}", s)
s.Width = 5
Console.WriteLine("Set Width: {0}", s)
Dim pi = s.GetType().GetProperty("Height")
Console.WriteLine("get property info: {0}", pi)
pi.SetValue(s, 10, Nothing)
Console.WriteLine("setting height with pi: {0}", s)
Dim box As Object = s 'same result with RuntimeHelpers.GetObjectValue(s)
Console.WriteLine("boxing: {0}", box)
pi.SetValue(box, 10, Nothing)
Console.WriteLine("setting value: {0}", box)
Console.WriteLine("")
Console.WriteLine("End test")
Console.ReadLine()
End Sub
End Module
The result given is:
Starting test
Created size: {Width=0, Height=0}
Set Width: {Width=5, Height=0}
get property info: Int32 Height
setting height with pi: {Width=5, Height=0} 'expected 5,10
boxing: {Width=5, Height=0}
setting value: {Width=5, Height=0} 'expected 5,10
End test
The same code is working (with boxing) in C#
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting test");
Size s= new Size();
Console.WriteLine("Created size: {0}", s);
s.Width = 5;
Console.WriteLine("Set Width: {0}", s);
PropertyInfo pi = s.GetType().GetProperty("Height");
Console.WriteLine("get property info: {0}", pi);
Console.WriteLine("can write?: {0}", pi.CanWrite);
pi.SetValue(s, 10, null);
Console.WriteLine("setting height with pi: {0}", s);
Object box = s; //same result with RuntimeHelpers.GetObjectValue(s)
Console.WriteLine("boxing: {0}", box);
pi.SetValue(box, 10, null);
Console.WriteLine("setting value: {0}", box);
Console.WriteLine("");
Console.WriteLine("End test");
Console.ReadLine();
}
}
Starting test
Created size: {Width=0, Height=0}
Set Width: {Width=5, Height=0}
get property info: Int32 Height
can write?: True
setting height with pi: {Width=5, Height=0}
boxing: {Width=5, Height=0}
setting value: {Width=5, Height=10}
End test
How do I make this work in VB?