RE: Passing reference type with 'ref' vs. without



The point of the ref keyword is to allow you to change the object that is
being passed into the method inside the method.

For example:

void DoSomething(ArrayList exampleList)
{
exampleList.Add("Something");
}

The caller of this method will see the changes made to the arraylist....
i.e. it will see the new entry.

However, with

void DoSomething(ArrayList exampleList)
{
exampleList = new ArrayList();
exampleList.Add("Something");
}

the caller will not see the new item as the reference inside the method has
changed. For the caller to be able to see the new item in the new list the
method signature would be:

void DoSomething(ref ArrayList exampleList)

And, ref is used for allowing you to pass value types by reference.

"Lenn" wrote:

> Hi,
>
> Could someone clarify my confusion regarding passing reference types to a
> method with ref keyword and explain when it's practical to use it.
>
> It's my understanding that in .NET reference types hold a reference to an
> object as opposed to object data itself. So, when reference type parameter is
> passed into a method, a copy of objects reference is passed in, so called
> method can do whatever to "original" object and a caller will see those
> changes.
> But if one adds "ref" keyword the actual address of a variable that holds
> object's reference is passed in, Which accomplishes the same thing as above
> scenario (without ref), but far more dangerous. My questions:
>
> 1. Is my overall understanding accurate?
> 2. What are some practical (real life) usages for passing reference type
> with ref.
> 3. Is there any performance benefits ref vs. without ref.
>
>
> Thanks
.



Relevant Pages

  • Re: Passing arguements by reference
    ... but doSomething doesnt change p unless i use "ref"? ... reference, hence both p and q pointing to the same object, not to different ... don't use the ref keyword. ... void Execute() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Documentation suggestions
    ... > Ian> I think it would be very useful if there was reference (not just ... Lang ref as only for "language lawyers". ...
    (comp.lang.python)
  • Re: pass by reference
    ... focus has moved from insisting to use "by ref" in java-context ... independent of any other use of the word "reference" in a language. ... Just because Java-refs can be re-targetted by assignment? ... If Java had an operator to tell an Object ...
    (comp.lang.java.programmer)
  • Re: error C2061: syntax error : identifier ref
    ... a 'ref' keyword to pass by reference. ... void f2 ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Texas TMS1232 Delta Sigma converters
    ... John Larkin writes: ... >>picked up between the transducer and the ADC I'm trying to eliminate. ... the reference problem is serious. ... We're using an Analog Devices Xfet ref, ADR421, ...
    (sci.electronics.design)