Why do you use the ref keyword when passing an object?

Why do you use the ref keyword when passing an object?

Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref keyword is used you’ve got a reference to a reference. This allows you to do things as described in the example given above.

When do you pass a parameter to a method?

In .NET when you pass any parameter to a method, a copy is created. In value types means that any modification you make to the value is at the method scope, and is lost when you exit the method. When passing a Reference Type, a copy is also made, but it is a copy of a reference, i.e. now you have TWO references in memory to the same object.

Can a method parameter be modified by ref?

A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword, as shown in the following example.

When to use the ref keyword in a method signature?

The ref keyword indicates that a value is passed by reference. It is used in four different contexts: In a method signature and in a method call, to pass an argument to a method by reference.

What happens if you pass T as a ref?

Since TestRef is a class (which are reference objects), you can change the contents inside t without passing it as a ref. However, if you pass t as a ref, TestRef can change what the original t refers to. i.e. make it point to a different object.

What happens if Foo is passed without ref?

If foo is passed to a method without using ref, that method might make changes to Object #24601. As a consequence of such changes, foo.Length might no longer equal 4. The method itself, however, will be unable to change foo, which will continue to hold “Object #24601”.

What happens when you pass a reference type?

When passing a Reference Type, a copy is also made, but it is a copy of a reference, i.e. now you have TWO references in memory to the same object. So, if you use the reference to modify the object, it gets modified.