Re: when to use "ref" and when not? please help!
From: Morten Wennevik (MortenWennevik_at_hotmail.com)
Date: 03/03/05
- Next message: Tony Fabian: "How to pass pass XmlResolver to Transform() method?"
- Previous message: Michael Grabelkovsky: "C# progam can't manage WM_KEYDOWN with VK_UP, VK_DOWN ?"
- In reply to: Tee: "when to use "ref" and when not? please help!"
- Next in thread: Bruce Wood: "Re: when to use "ref" and when not? please help!"
- Reply: Bruce Wood: "Re: when to use "ref" and when not? please help!"
- Messages sorted by: [ date ] [ thread ]
Date: Thu, 03 Mar 2005 11:04:43 +0100
Hi Tee,
ref is handy when the reference might get changed in a method and you want
to be able to use the new object, and it is handy in methods where you
want multiple objects returned instead of just one.
Consider this code
ArrayList list = new ArrayList();
list.Add("Hello");
list.Add("World");
DoSomething(list);
int n = list.Count; // n = 3 because "Tee" is now added
DoSomethingElse(list)
int o = list.Count; // n = 3 because list still references the original
ArrayList
DoSomethingAgain(ref list)
int p = list.Count; // n = 0 because list now references the new ArrayList
...
void DoSomething(ArrayList list)
{
list.Add("Tee");
}
void DoSomethingElse(ArrayList list)
{
list = new ArrayList();
}
void DoSomethingAgain(ref ArrayList list)
{
list = new ArrayList();
}
...
When we use this method for parsing a string containing a double the
method returns true or false. If the method returns true, the string
contained a valid double but to be able to get the double we pass it an
empty double.
'out' is the same as 'ref' but you do not need to reference a valid object
before you call a method, but you do need to set the reference to
something before you return (with ref you do not need to set the reference
inside the method).
public static bool TryParse(string s, NumberStyles style, IFormatProvider
provider, out double result);
...
double d;
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
bool result = Double.TryParse("12", NumberStyles.Any, ci.NumberFormat, out
d);
if(result)
MessageBox.Show("We got a valid number: " + d); // 12
-- Happy Coding! Morten Wennevik [C# MVP]
- Next message: Tony Fabian: "How to pass pass XmlResolver to Transform() method?"
- Previous message: Michael Grabelkovsky: "C# progam can't manage WM_KEYDOWN with VK_UP, VK_DOWN ?"
- In reply to: Tee: "when to use "ref" and when not? please help!"
- Next in thread: Bruce Wood: "Re: when to use "ref" and when not? please help!"
- Reply: Bruce Wood: "Re: when to use "ref" and when not? please help!"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|
|