Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
VB.Net: Set a readonly propery via reflection
From Wiki
This is only to be used for testing purposes else what is the point of readonly properties ;-).
- Imports System.IO
- Module Module1
- Sub Main()
- Dim _test As Test
- _test = New Test
- Console.WriteLine(_test.Id)
- Dim p As System.Reflection.FieldInfo = _test.GetType.GetField("_id", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
- p.SetValue(_test, 1)
- Console.WriteLine(_test.Id)
- Console.ReadLine()
- End Sub
- End Module
- Public Class Test
- Private _id As Integer
- Public Sub New()
- _id = 0
- End Sub
- Public ReadOnly Property Id() As Integer
- Get
- Return _id
- End Get
- End Property
- End Class
As you can see there is no way to set the property directly but we use the corresponding field fo this to work.



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.