passing "this" by reference
-
hi, I originally wrote an object as a struct, and now I am changing it to a class. In one of my member methods I want to pass "this" by reference to a method in another class and I get teh below error when I try to build? Is this common? Anyone know why it works with a struct and not a class? Cannot pass '' as a ref or out argument because it is read-only thanks cb
-
hi, I originally wrote an object as a struct, and now I am changing it to a class. In one of my member methods I want to pass "this" by reference to a method in another class and I get teh below error when I try to build? Is this common? Anyone know why it works with a struct and not a class? Cannot pass '' as a ref or out argument because it is read-only thanks cb
Hi, for structs, ints and other simple data types, "this" is the value itself (hence the name "value types"); you may add the "ref" keyword to obtain a reference to it (similar to a pointer in C/C++). for class instances, "this" is a reference (hence "reference types"), so it behaves as a pointer would in C/C++; hence you should drop the "ref" all together when switching from struct to class. :)
Luc Pattyn [My Articles]
-
hi, I originally wrote an object as a struct, and now I am changing it to a class. In one of my member methods I want to pass "this" by reference to a method in another class and I get teh below error when I try to build? Is this common? Anyone know why it works with a struct and not a class? Cannot pass '' as a ref or out argument because it is read-only thanks cb
Hi, as Luc already suggested, you can just drop the 'ref' from your method's parameter and everything should work. I will just add some explanation why you must not pass 'this' as a ref parameter. If you have a value object (a struct) and you pass it by value (no 'ref' parameter) to the method, the method gets its own copy and the original will not be affected by any changes made in the method. If the value object is passed by reference, all changes do affect the original. If you have a reference object (a class) and you pass it by value, the reference itself is copied. Thus you have two references to the same object. If the method changes the referenced object, the changes will affect the original. However, if the method changes the reference itself (e.g. set it to 'null'), this will not affect the original reference. If you pass the reference object as a reference parameter, you are able not only to manipulate the referenced object but also the reference itself. Sometimes this is the desired behaviour, but you definitely don't want enable any method to set your 'this' reference to 'null'. Therefore 'this' is read-only and must not be passed by reference. Hope this helps.
Regards, Tim