473,842 Members | 1,594 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

when to use "ref" and when not? please help!

Tee
Hi guys,

I am confused about the usage of "ref".

Please see this code:

private void button3_Click(o bject sender, System.EventArg s e)

{

DataTable dt = new DataTable();

AddColumn(dt);

Console.WriteLi ne(dt.Namespace );

RefAddColumn(re f dt);

Console.WriteLi ne(dt.Namespace );

}

private void AddColumn(DataT able table)

{

table.Namespace = "NoRef";

}

private void RefAddColumn(re f DataTable table)

{

table.Namespace = "Ref";

}

In this case, ref and without ref have no difference. The table got the
namespace changed.

But in this piece of code,

private void button4_Click(o bject sender, System.EventArg s e)

{

char i = 'a';

TestRef(ref i);

Console.WriteLi ne(i);

TestNoRef(i);

Console.WriteLi ne(i);

}

private void TestRef(ref char i)

{

i = 'b';

}

private void TestNoRef(char i)

{

i = 'c';

}

only the one with "ref" works for this "char i"...

why ref & without-ref work for DataTable but not char i?? Can anyone tell
me?

Thanks,

Tee
Nov 16 '05 #1
5 6710
"Tee" <th*@streamyx.c om> a écrit dans le message de news:
#w************* *@TK2MSFTNGP10. phx.gbl...
why ref & without-ref work for DataTable but not char i?? Can anyone tell
me?


Because you only changed a member of DataTable, not the DataTable object
itself, whereas you changed the object being pointed to for char i.

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 16 '05 #2
Tee,

Because that one of the big differences between a value and a reference to
an object.

A value passes his value in the value
An object passes his reference in the value
A ref boxes the reference in both situation in the passed value

I hope this helps?

Cor
Nov 16 '05 #3
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(lis t);

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

DoSomethingAgai n(ref list)

int p = list.Count; // n = 0 because list now references the new ArrayList

....

void DoSomething(Arr ayList list)
{
list.Add("Tee") ;
}

void DoSomethingElse (ArrayList list)
{
list = new ArrayList();
}

void DoSomethingAgai n(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.Threadin g.Thread.Curren tThread.Current Culture;

bool result = Double.TryParse ("12", NumberStyles.An y, ci.NumberFormat , out
d);

if(result)
MessageBox.Show ("We got a valid number: " + d); // 12
--
Happy Coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #4
You also might want to read Jon Skeet's article on parameter passing:

http://www.yoda.arachsys.com/csharp/parameters.html

Nov 16 '05 #5
Tee
Thanks for everyone who replied!
Now I understand it better. Thank you.

Tee.
"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
You also might want to read Jon Skeet's article on parameter passing:

http://www.yoda.arachsys.com/csharp/parameters.html

Nov 16 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1986
by: Dmitry | last post by:
Hi, I have defined interface for COM components which inludes an argument being filled with additional error info, if such occurs. If inside I raise COM Error, I populate that parameter. In COM environment this architecture works beautifully -- caller application gets negative HRESULT and error description from IErrorInfo object, and additional "log" information from that "ref" parameter: In .Net it just never returns that paramter...
22
3358
by: Dr Duck | last post by:
GDay all, Something seems odd to me.... I wrote a simple C# function public void bind(ref object a, ref object b, bool atob) { if(atob) b = a; else
11
2209
by: Doug | last post by:
Is there any harm in passing an object into a method with the 'ref' keyword if the object is already a reference variable? If not, is there any benefit?
3
1312
by: Stephen Gennard | last post by:
Hello, I having a problem dynamically invoking a static method that takes a reference to a SByte*. If I do it directly it works just fine. Anyone any ideas why? I have include a example below... --
1
1276
by: Kris Takacs | last post by:
Hello, I recently upgraded a project from Visual Studio 6 to .NET and get the following error message when I call help: "The window name "REF" was not defined in your project file." If I click OK, the help comes up... Any ideas?
5
2682
by: Cmtk Software | last post by:
The following code: public __gc class MyClass { public: void MyFunc (int __gc* number); }; Generates the following metadata for C# when compiled in VC 2005 with the /clr:oldsyntax switch in a DLL project:
0
9872
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9715
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10945
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10612
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10314
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9453
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7858
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
4089
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3145
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.