RE: Passing reference type with 'ref' vs. without
- From: Brian Delahunty <BrianDelahunty@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 4 Aug 2005 12:40:05 -0700
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
.
- References:
- Prev by Date: Re: Passing reference type with 'ref' vs. without
- Next by Date: Re: Passing reference type with 'ref' vs. without
- Previous by thread: Re: Passing reference type with 'ref' vs. without
- Next by thread: Re: Passing reference type with 'ref' vs. without
- Index(es):
Relevant Pages
|