473,396 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

ref?

Hey guys

I need some clarification.

The ref keyword means that you pass in a reference to an object or variable,
is it like the & and * of c++?

What i don't understand is, in c#, it always uses reference by i thought,
or is it only refs on classes?

so if i do

someobj so = new someObj(); //so memory allocated

so.someVar = 10; //somevar set to 10

someobj so2 = so; //they now equal each other, so2 is using a ref as we did
not clone it

so2.someVar = 20; //when we do this, so.someVar also becomes 20

Console.Writeline(so.someVar.ToString());

//would print out 20

Isn't that right? If that is the case, why the ref keyword and when would
you need it?



Jan 10 '07 #1
15 1530
What i don't understand is, in c#, it always uses reference by i thought,
or is it only refs on classes?
Memory is allocated on the stack and the heap; this translates to
primitive "value types" and "reference types." An integer or boolean
is stored by value, whereas instances of classes are created with the
new keyword and then managed by reference, where in your code you have
to variables that are both references to the same object in memory, and
when one makes a change, the other will see it.

Counter-intuitively, though, structs are value types. So if you use "x
= y;" in your code you're cloning the values, not using two pointers to
the same location.

Jan 10 '07 #2
'ref' and 'out' are used with method params. Here are some examples
that should get the idea across..

void Test1(int val)
{
val++;
}
void Test2(ref int val)
{
val++;
}
void Test3(out int val)
{
val++;
}
int myInt = 5;

Test1(myInt);
// myInt still equals 5.
// The procedure modified its own copy of the data.

Test2(ref myInt); // The 'ref' is nessisary here.
// myInt now equals 6.
// The procedure was given a reference to the 'myInt' var directly.

Test3(out myInt); // The 'out' is nessisary here as well.
// myInt now equals 1.
// The procedure was given a fresh new reference, but 'myInt' was
replaced with that new reference.
Daniel wrote:
Hey guys

I need some clarification.

The ref keyword means that you pass in a reference to an object or variable,
is it like the & and * of c++?

What i don't understand is, in c#, it always uses reference by i thought,
or is it only refs on classes?

so if i do

someobj so = new someObj(); //so memory allocated

so.someVar = 10; //somevar set to 10

someobj so2 = so; //they now equal each other, so2 is using a ref as we did
not clone it

so2.someVar = 20; //when we do this, so.someVar also becomes 20

Console.Writeline(so.someVar.ToString());

//would print out 20

Isn't that right? If that is the case, why the ref keyword and when would
you need it?
Jan 10 '07 #3
Hi,

The ref keyword is used for passing method arguments by reference and has
nothing to do with property or field assignment. It's observable behavior
is the same for value-types and reference types, however, the reasons for it
are somewhat less trivial.

In the code below, "localVar", a System.Boolean, is a value type. Passing
it in by-reference is like passing in a pointer to the location of the
variable within the TestRef method.

void TestRef()
{
bool localStruct = false;

UpdateMyLocalVariable(ref localStruct);

Console.WriteLine(localStruct); // true
}

void UpdateMyLocalVariable(ref bool localStruct)
{
// update the reference to localStruct
// so that *it is* a new value
localStruct = true;
}

In the following code an object reference is updated. Note, it's the
reference that is being passed by-reference, not what it normally points to,
which is the actual location of the object in memory.

void TestRefObject()
{
object localObject= new object();

UpdateMyLocalVariable(ref localObject);

Console.WriteLine(localObject); // "A string object";
}

void UpdateMyLocalVariable(ref object localObject)
{
// update the reference to localObject
// so *it points to* a string (which is an object)
localObject = "A string object";
}
When you pass a value by-reference you're passing in a reference to the
value where it exists on the stack or the heap, not a copy as is
traditionally sent for value-types.

When you pass an object by-reference you're passing in the reference itself,
not what it points to - the object. Traditionally, when you pass an object,
you're passing in the location of the object on the heap. By-ref, you're
passing in the reference to the location on the heap instead.

--
Dave Sexton
http://davesexton.com/blog

"Daniel" <Da*****@vestryonline.comwrote in message
news:ui**************@TK2MSFTNGP02.phx.gbl...
Hey guys

I need some clarification.

The ref keyword means that you pass in a reference to an object or
variable, is it like the & and * of c++?

What i don't understand is, in c#, it always uses reference by i thought,
or is it only refs on classes?

so if i do

someobj so = new someObj(); //so memory allocated

so.someVar = 10; //somevar set to 10

someobj so2 = so; //they now equal each other, so2 is using a ref as we
did not clone it

so2.someVar = 20; //when we do this, so.someVar also becomes 20

Console.Writeline(so.someVar.ToString());

//would print out 20

Isn't that right? If that is the case, why the ref keyword and when would
you need it?



Jan 10 '07 #4
<Fo**********@gmail.comwrote:
What i don't understand is, in c#, it always uses reference by i thought,
or is it only refs on classes?

Memory is allocated on the stack and the heap; this translates to
primitive "value types" and "reference types."
No, it doesn't.

See http://www.pobox.com/~skeet/csharp/memory.html
An integer or boolean is stored by value, whereas instances of
classes are created with the new keyword and then managed by
reference, where in your code you have to variables that are both
references to the same object in memory, and when one makes a change,
the other will see it.

Counter-intuitively, though, structs are value types. So if you use "x
= y;" in your code you're cloning the values, not using two pointers to
the same location.
Why is that counter-intuitive for you, out of interest?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 10 '07 #5
Daniel <Da*****@vestryonline.comwrote:
I need some clarification.

The ref keyword means that you pass in a reference to an object or variable,
is it like the & and * of c++?

What i don't understand is, in c#, it always uses reference by i thought,
or is it only refs on classes?
See http://www.pobox.com/~skeet/csharp/parameters.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 10 '07 #6
In message MP************************@msnews.microsoft.com,
Jon Skeet [C# MVP] <sk***@pobox.comProclaimed from the tallest tower:
<Fo**********@gmail.comwrote:
>>What i don't understand is, in c#, it always uses reference by i
thought, or is it only refs on classes?

Memory is allocated on the stack and the heap; this translates to
primitive "value types" and "reference types."

No, it doesn't.

See http://www.pobox.com/~skeet/csharp/memory.html
>An integer or boolean is stored by value, whereas instances of
classes are created with the new keyword and then managed by
reference, where in your code you have to variables that are both
references to the same object in memory, and when one makes a change,
the other will see it.

Counter-intuitively, though, structs are value types. So if you use
"x = y;" in your code you're cloning the values, not using two
pointers to the same location.

Why is that counter-intuitive for you, out of interest?
Maybe not counter-intuitiave, but slightly confusing at times. It can
sometimes not be clear straight away if you are dealing with a class or a
struct, especially if you are reading a large chunk of someone elses code.
Then again, what is the logical reason for structs behaving differently in
this way?

--
Regards,
Chris.
(Remove Elvis's shoes to email me)
Jan 10 '07 #7
Hi jon thanks for the article it was very helpful.

Do you happen to have an article which explains what the stack/heap is,
or know of any good article that does likewise?

Thanks,

Gary.

On Jan 10, 7:22 am, Jon Skeet [C# MVP] <s...@pobox.comwrote:
Daniel <Dani...@vestryonline.comwrote:
I need some clarification.
The ref keyword means that you pass in a reference to an object or variable,
is it like the & and * of c++?
What i don't understand is, in c#, it always uses reference by i thought,
or is it only refs on classes?Seehttp://www.pobox.com/~skeet/csharp/parameters.html

--
Jon Skeet - <s...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 10 '07 #8
ChrisM <ch**************@suedeyahoo.comwrote:
Counter-intuitively, though, structs are value types. So if you use
"x = y;" in your code you're cloning the values, not using two
pointers to the same location.
Why is that counter-intuitive for you, out of interest?

Maybe not counter-intuitiave, but slightly confusing at times. It can
sometimes not be clear straight away if you are dealing with a class or a
struct, especially if you are reading a large chunk of someone elses code.
Then again, what is the logical reason for structs behaving differently in
this way?
The whole point of having structs and classes is to have both value
type behaviour and reference type behaviour. When you want a type to
behave with reference type semantics, use a class. When you want a type
to behave with value type semantics, use a struct.

It's very, very rare to want to define your own value type - usually
you'll be using the predefined value types (int etc, Guid, DateTime...)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 10 '07 #9
Gary <ga********@myway.comwrote:
Hi jon thanks for the article it was very helpful.

Do you happen to have an article which explains what the stack/heap is,
or know of any good article that does likewise?
I don't know of a good article, I'm afraid.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 10 '07 #10
"Daniel" <Da*****@vestryonline.comwrote in message
news:ui**************@TK2MSFTNGP02.phx.gbl...
Hey guys

I need some clarification.

The ref keyword means that you pass in a reference to an object or
variable, is it like the & and * of c++?
The closest thing to the ref keyword in C# would be **.
Not only can you modify the object, you can replace the object with a
new object.

Bill


Jan 11 '07 #11

Yota wrote:
'ref' and 'out' are used with method params. Here are some examples
that should get the idea across..

void Test1(int val)
{
val++;
}
void Test2(ref int val)
{
val++;
}
void Test3(out int val)
{
val++;
}
int myInt = 5;

Test1(myInt);
// myInt still equals 5.
// The procedure modified its own copy of the data.

Test2(ref myInt); // The 'ref' is nessisary here.
// myInt now equals 6.
// The procedure was given a reference to the 'myInt' var directly.

Test3(out myInt); // The 'out' is nessisary here as well.
// myInt now equals 1.
// The procedure was given a fresh new reference, but 'myInt' was
replaced with that new reference.

Method Test3 won't even compile: the "out" modifier indicates that
"val" can be passed in without being initialized, and incrementing an
uninitialized variable is a no-no. Test3 would have to be written like
this:

void Test3(out int val)
{
val = 0;
val++;
}

or something like that.

Jan 11 '07 #12

Jon Skeet [ C# MVP ] wrote:
Gary <ga********@myway.comwrote:
Hi jon thanks for the article it was very helpful.

Do you happen to have an article which explains what the stack/heap is,
or know of any good article that does likewise?

I don't know of a good article, I'm afraid.
This one seems to provide a good introduction:

http://www.c-sharpcorner.com/UploadF...5-413b6d348b91

(Google is your friend!)

Jan 11 '07 #13
Counter-intuitively, though, structs are value types. So if you use "x
= y;" in your code you're cloning the values, not using two pointers to
the same location.
Why is that counter-intuitive for you, out of interest?
Because structs aren't primatives, and because you can write an
initializer, and then (seemingly) create instances of the struct. My
thinking is that creating an instance means allocating a slot of memory
and populating it ... then accessing it later through a pointer. I
realize that type initializers in structs are there for convenience, to
set a bunch of values with one line of code, but in practice ... it
just seems counter-intuitive to me.

Jan 11 '07 #14
Hi Daniel,

the ref and out keyword means you are passing a variable instead of a value
resp. an object.
So the called method will be able to assign to the variable given by the
caller.

A parameter without ref or out is like a local variable, wich is assigned by
the caller.

"Daniel" <Da*****@vestryonline.comschrieb im Newsbeitrag
news:ui**************@TK2MSFTNGP02.phx.gbl...
Hey guys

I need some clarification.

The ref keyword means that you pass in a reference to an object or
variable, is it like the & and * of c++?

What i don't understand is, in c#, it always uses reference by i thought,
or is it only refs on classes?

so if i do

someobj so = new someObj(); //so memory allocated

so.someVar = 10; //somevar set to 10

someobj so2 = so; //they now equal each other, so2 is using a ref as we
did not clone it

so2.someVar = 20; //when we do this, so.someVar also becomes 20

Console.Writeline(so.someVar.ToString());

//would print out 20

Isn't that right? If that is the case, why the ref keyword and when would
you need it?



Jan 11 '07 #15
<Fo**********@gmail.comwrote:
Counter-intuitively, though, structs are value types. So if you use "x
= y;" in your code you're cloning the values, not using two pointers to
the same location.
Why is that counter-intuitive for you, out of interest?

Because structs aren't primatives, and because you can write an
initializer, and then (seemingly) create instances of the struct.
Yup - but they're still value types.
My thinking is that creating an instance means allocating a slot of memory
and populating it ... then accessing it later through a pointer.
That thinking is what's wrong.
I realize that type initializers in structs are there for convenience, to
set a bunch of values with one line of code, but in practice ... it
just seems counter-intuitive to me.
Do you have a C++ background? If so, maybe it's a "new implies
pointer" instinct.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 11 '07 #16

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

Similar topics

3
by: William C. White | last post by:
Does anyone know of a way to use PHP /w Authorize.net AIM without using cURL? Our website is hosted on a shared drive and the webhost company doesn't installed additional software (such as cURL)...
2
by: Albert Ahtenberg | last post by:
Hello, I don't know if it is only me but I was sure that header("Location:url") redirects the browser instantly to URL, or at least stops the execution of the code. But appearantely it continues...
3
by: James | last post by:
Hi, I have a form with 2 fields. 'A' 'B' The user completes one of the fields and the form is submitted. On the results page I want to run a query, but this will change subject to which...
0
by: Ollivier Robert | last post by:
Hello, I'm trying to link PHP with Oracle 9.2.0/OCI8 with gcc 3.2.3 on a Solaris9 system. The link succeeds but everytime I try to run php, I get a SEGV from inside the libcnltsh.so library. ...
1
by: Richard Galli | last post by:
I want viewers to compare state laws on a single subject. Imagine a three-column table with a drop-down box on the top. A viewer selects a state from the list, and that state's text fills the...
4
by: Albert Ahtenberg | last post by:
Hello, I have two questions. 1. When the user presses the back button and returns to a form he filled the form is reseted. How do I leave there the values he inserted? 2. When the...
1
by: inderjit S Gabrie | last post by:
Hi all Here is the scenerio ...is it possibly to do this... i am getting valid course dates output on to a web which i have designed ....all is okay so far , look at the following web url ...
2
by: Jack | last post by:
Hi All, What is the PHP equivilent of Oracle bind variables in a SQL statement, e.g. select x from y where z=:parameter Which in asp/jsp would be followed by some statements to bind a value...
3
by: Sandwick | last post by:
I am trying to change the size of a drawing so they are all 3x3. the script below is what i was trying to use to cut it in half ... I get errors. I can display the normal picture but not the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.