Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

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

Navigation

Google Ads

VB.Net: Set a readonly propery via reflection

From Wiki

Jump to: navigation, search

This is only to be used for testing purposes else what is the point of readonly properties ;-).

  1. Imports System.IO
  2.  
  3. Module Module1
  4.  
  5.     Sub Main()
  6.         Dim _test As Test
  7.         _test = New Test
  8.         Console.WriteLine(_test.Id)
  9.         Dim p As System.Reflection.FieldInfo = _test.GetType.GetField("_id", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
  10.         p.SetValue(_test, 1)
  11.         Console.WriteLine(_test.Id)
  12.         Console.ReadLine()
  13.     End Sub
  14.  
  15. End Module
  16.  
  17. Public Class Test
  18.     Private _id As Integer
  19.  
  20.     Public Sub New()
  21.         _id = 0
  22.     End Sub
  23.  
  24.     Public ReadOnly Property Id() As Integer
  25.         Get
  26.             Return _id
  27.         End Get
  28.     End Property
  29. 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.

533 Rating: 1.4/5 (5 votes cast)