Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass this by ref in C#?

In a class (ClassA) of mine I want to create a related instance of another class (ClassB) providing it with a reference to the object who has initiated it's creation. So I've provided ClassB with a construcror taking a (ref ClassB master) argument. But in ClassA I can't just call var slave = new ClassB(ref this). How to implement this?

like image 435
Ivan Avatar asked Jun 29 '11 22:06

Ivan


People also ask

Why do we pass by value and pass by reference in C?

C always uses 'pass by value' to pass arguments to functions (another term is 'call by value', which means the same thing), which means the code within a function cannot alter the arguments used to call the function, even if the values are changed inside the function.

Why is there no pass by reference in C?

C doesn't have this concept. In C when passing a pointer, the syntax requires a dereference to be applied to get the value, whereas in true pass-by-reference languages such as Pascal (parameters declared with var) and C++ (parameters declared with &), that requirement doesn't exist.

How arguments are passed to a function using references?

The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.


1 Answers

You don't need to pass by ref in this case. If you are passing ClassB(this), it will be passed by reference and not by value anyway. Any changes made to the classA instance passed into classB's constructor will be applied to class A as well.

like image 142
TheITGuy Avatar answered Sep 22 '22 07:09

TheITGuy