Groups | Blog | Home
all groups > dotnet academic > december 2004 >

dotnet academic : System.Reflection question



Erol
12/14/2004 12:47:06 AM
I have two code snipets, one in VB and the other in C#. Why does the visual
basic example not change the structure member "x", but the C# code does? I
need the visual basic code to work as I am a visual basic coder, but I don't
know what is wrong. Is there a bug in visual basic.net? Please help!


'VB Code
Imports System
Imports System.Reflection

Structure Foo
Public x As Integer
End Structure

Class Test

Shared Sub Main()
Dim f As New Foo
f.x = 10

Dim fi As FieldInfo = GetType(Foo).GetField("x")

Dim o As Object = f
fi.SetValue(o, 3)
f = CType(o, Foo)

Console.WriteLine(f.x)
End Sub
End Class




//C#
using System;
using System.Reflection;

struct Foo
{
public int x;
}

Class Test
{
static void Main()
{
Foo f = new Foo();
f.x = 10;

FieldInfo fi = typeof(Foo).GetField("x");

object o = f;
fi.SetValue (o, 3);
f = (Foo)o;

Console.WriteLine (f.x);
}
}

--
Mattias Sjögren
12/14/2004 12:44:14 PM

[quoted text, click to view]

It has to do with how VB treats boxed value types.

To get the behavior you want, change the type of the o variable to
ValueType instead of Object.


[quoted text, click to view]

This is by design.



Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Erol
12/14/2004 10:15:03 PM
Thank-you very much - it works just fine. You were the only one out of
seventeen experts that I asked who could come up with the solution.

Thanks!

[quoted text, click to view]
AddThis Social Bookmark Button