c# - Reference To Variable, Not To Object -
i'd if make reference point specific variable rather object (or memory location more accurately) variable representing.
as example let's have following program, want create reference myclass returns whatever value in myclass @ times, if value changes. have code looks like.
class myclass { public int value = 0; } class program { static myclass saved; //maintained , used following 2 functions static void storereference(myclass input) { saved = input; } static void setvalue() { saved.value = 42; } static void main(string[] args) { //a couple arbitrary classes i'd have references myclass = new myclass(); myclass b = new myclass(); storereference(a); = b; setvalue(); console.write(a.value); //should print 42, instead prints 0 since reads in original object set } }
is there can in c#, or can prevent variable being assigned new memory location (so above code return error @ = b)?
you can check whether saved
has value or not:
static void storereference(myclass input) { if (saved != null) { return; } saved = input; }
Comments
Post a Comment