Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a property reference using reflection

Tags:

c#

reflection

var a = new obj();
var property = a.GetType().GetProperty("DB").GetValue(a,null) as testObject;

does this mean that the variable property hold a reference to the the same object that i got in object a , or a new testObject was made that holds the same values?

if this means creating a new object, then how can i get the reference to that property/backing field using reflection?

like image 760
user1492051 Avatar asked Jan 01 '14 18:01

user1492051


2 Answers

property now holds a referece to whatever is in a's DB property.

I'm not sure though what happens when you call GetValue() on a property that has a value type, I suppose you get a reference to a boxed copy of the original value, as explained in Boxing and Unboxing (C# Programming Guide):

Boxing a value type [to object in GetValue()'s case] allocates an object instance on the heap and copies the value into the new object.

like image 70
CodeCaster Avatar answered Oct 02 '22 05:10

CodeCaster


Variable property holds reference to same value stored in property DB.

GetValue(a,null) return type is object so with as operator you are simple type casting it.

like image 37
Rohit Vats Avatar answered Oct 02 '22 04:10

Rohit Vats