473,768 Members | 5,334 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A question about passing an object by reference

Hello all,

I'm passing a reference to a class into the constructor of a form, like
so: public MyForm(int count, ref Area myArea) {...}

How can I use myArea outside the constructor? Should I create another
Area and assign myArea to it (ie: Area foo = myArea;) or is there a
better way?

~AF

Nov 15 '05 #1
13 17930
Here is how I would write it:

private int _count;
private Area _myArea;

public MyForm(int count, Area myArea) { _count = count; _myArea =
myArea; }

// Now, you can use _myArea in any method, like:
public void DoSomethingWith MyArea() { _myArea.DoSomet hing(); }

Note: You do not need the ref keyword in the constructor because objects are
always passed "by reference" in C#. So, with the code above (no ref
keyword), _myArea and myArea point to the same object, which is probably
what you want.

The ref keyword really means in/out. It means that the caller passes one
object and receives a different object when the call completes (so, you are
not passing a reference to the object, but rather a reference to a reference
(*) ). It is only useful when a method needs to return several results.

(*) This is a slight simplification of the real picture because in C# the
assignment of the new value is done by the caller rather than by the callee
(so that you can pass a property with a pair of r/w accessors), so if you
use the ref keyword, the value is copied to a temporary variable before the
call, the callee receives the address of the temporary variable, the callee
writes its new value to the temporary variable, and then the caller assigns
the temporary variable to the argument (which must be a valid target for
assignment) after the call completes.

Bruno.

"Abe Frohnman" <us******@SPAMe xperimentzero.o rg> a écrit dans le message de
news:sM******** **************@ news.easynews.c om...
Hello all,

I'm passing a reference to a class into the constructor of a form, like
so: public MyForm(int count, ref Area myArea) {...}

How can I use myArea outside the constructor? Should I create another
Area and assign myArea to it (ie: Area foo = myArea;) or is there a
better way?

~AF

Nov 15 '05 #2
Bruno Jouhier [MVP] <bj******@clu b-internet.fr> wrote:
Note: You do not need the ref keyword in the constructor because objects are
always passed "by reference" in C#.


No they're not. References are passed by value. I know it may be easier
to say this than to explain it fully, but I think it does harm in the
end.

To the OP: see http://www.pobox.com/~skeet/csharp/parameters.html for a
full discussion about what "passing by reference" really means, and
what C# does.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #3
Hmm...so C# passes objects differently than C++ does? I know that if you
don't explicitly tell a C++ function/method that the object is going to
be passed in by reference, it gets passed in by value. So just to ensure
that I'm understanding this correctly, whenever I pass an object into a
function/method it'll >always< be passed in by reference? And any
changes I make to that object in the method will affect the object
outside of that method?

AF

Bruno Jouhier [MVP] wrote:
Here is how I would write it:

private int _count;
private Area _myArea;

public MyForm(int count, Area myArea) { _count = count; _myArea =
myArea; }

// Now, you can use _myArea in any method, like:
public void DoSomethingWith MyArea() { _myArea.DoSomet hing(); }

Note: You do not need the ref keyword in the constructor because objects are
always passed "by reference" in C#. So, with the code above (no ref
keyword), _myArea and myArea point to the same object, which is probably
what you want.

The ref keyword really means in/out. It means that the caller passes one
object and receives a different object when the call completes (so, you are
not passing a reference to the object, but rather a reference to a reference
(*) ). It is only useful when a method needs to return several results.

(*) This is a slight simplification of the real picture because in C# the
assignment of the new value is done by the caller rather than by the callee
(so that you can pass a property with a pair of r/w accessors), so if you
use the ref keyword, the value is copied to a temporary variable before the
call, the callee receives the address of the temporary variable, the callee
writes its new value to the temporary variable, and then the caller assigns
the temporary variable to the argument (which must be a valid target for
assignment) after the call completes.


Nov 15 '05 #4
Abe Frohnman <us******@SPAMe xperimentzero.o rg> wrote:
Hmm...so C# passes objects differently than C++ does? I know that if you
don't explicitly tell a C++ function/method that the object is going to
be passed in by reference, it gets passed in by value. So just to ensure
that I'm understanding this correctly, whenever I pass an object into a
function/method it'll >always< be passed in by reference? And any
changes I make to that object in the method will affect the object
outside of that method?


You never pass a reference type object at all - you only pass a
reference, and that reference is passed by value. Any change to the
object referred to is also seen via the reference outside the method -
there's only one actual object involved.

See http://www.pobox.com/~skeet/csharp/parameters.html for more
information.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #5
Abe Frohnman <us******@SPAMe xperimentzero.o rg> wrote:
Right, right. Sorry I've not yet had my morning coffee. :) Let me
rephrase that: In C#, objects are passed by reference automatically.
No, objects are never passed. References to objects are passed by
value. This is different to objects being passed by reference.
No need to use the 'ref' keyword in front of them?
That really depends on exactly what you want to do.
So if I have a class that takes a reference to an object in its
constructor, what's the best way to use that reference later in the class?

ie: MyForm(myClass foo) {...}

should the constructor do something like: this.foo = foo; or is there a
better way?


Assuming it has a foo field, then yes, that's perfectly okay.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #6
hehe, I suggest you have another cup of coffee :) You keep saying the
same thing...

lemme give it a try this time
In C#, objects are passed by reference automatically. No
need to use the 'ref' keyword in front of them?
Objects aren't passed.. objects are on the heap.. if you have something
like :

MyClass foo = new MyClass();

You instantiate an object which is then stored in the heap.. the
reference-type variable 'foo' is stored on the stack and holds the
reference to this object. when you pass this variable onto a method like:

MyForm f = new MyForm(MyClass foo2)

you actually pass the value of foo (which is the reference to the actual
object in the heap) to foo2.. foo2 is then stored on the stack with the
passed reference as its value which was 'copied' accross. Now, foo and
foo2 both have access to the heap-allocated object. If foo2 were to
change the object in some way, foo will be able to see the change -
however, since foo2 is another variable on the stack, making changes to
foo2 itself will not affect foo. Consider this:

MyForm(MyClass foo2) {

foo2 = new MyClass();

// foo2, above, now holds a reference to a newly allocated object
// foo, however, was not affected
}
-Andre

So if I have a class that takes a reference to an object in its
constructor, what's the best way to use that reference later in the class?

ie: MyForm(myClass foo) {...}

should the constructor do something like: this.foo = foo; or is there a
better way?

Thanks for the help!

Jon Skeet wrote:
You never pass a reference type object at all - you only pass a
reference, and that reference is passed by value. Any change to the
object referred to is also seen via the reference outside the method -
there's only one actual object involved.

See http://www.pobox.com/~skeet/csharp/parameters.html for more
information.


Nov 15 '05 #7
G
So what is the outcome of this?
Objects are always passed by reference or value?
Nov 15 '05 #8
They are passed by value.

-Andre

G wrote:
So what is the outcome of this?
Objects are always passed by reference or value?


Nov 15 '05 #9
Ming Chen [.NET MVP] <qq******@yahoo .com> wrote:
I'm not getting the context of the discussion. Here is just what I think
about your questions.
Generally speaking, ValueTypes are passed by value, while Reference types
are passed by reference by default.
No they are not. With reference types, the reference is passed by
value, which is a different thing to passing by reference.
See http://www.pobox.com/~skeet/csharp/parameters.html (again!)
For value types, it makes a lot sense to pass them by ref. Cause that's the
only way to change the parameter object value in a function.
For reference types, it still gives some bonus to pass them by ref.


.... which suggests that you *must* be wrong above, as if they are
passed by reference to start with, how could passing them by reference
give them some bonus?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #10

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

Similar topics

220
19148
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
58
10179
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
34
440
by: wilson | last post by:
Hi All, I am a novice at C and just have learned pointer for a short period. Today one error had occured while executing my program below. And I cannot find the error out since it's checked "OK" by Dev C++. Here is:(I want to exchange the value of "a" and "b" with function "swap") void swap(int *pa, int *pb) {
9
1970
by: Alvin Bruney | last post by:
The more knowledgable I get about this .net world, the more questions I have. ..NET uses pass by reference for all objects....uhhh I mean pass by value. (Couldn't resist this jab) Consider a string object whose value is passed as a parameter to a function. The reference is pointing back to memory allocated on the heap where the contents of the string lives. Inside the function, I adjust the value, say string += "value", which means on...
8
2118
by: Dennis Myrén | last post by:
I have these tiny classes, implementing an interface through which their method Render ( CosWriter writer ) ; is called. Given a specific context, there are potentially a lot of such objects, each requiring a call to that method to fulfill their purpose. There could be 200, there could be more than 1000. That is a lot of references passed around. It feels heavy. Let us say i changed the signature of the interface method to:
11
8128
by: John Pass | last post by:
Hi, In the attached example, I do understand that the references are not changed if an array is passed by Val. What I do not understand is the result of line 99 (If one can find this by line number) which is the last line of the following sub routine: ' procedure modifies elements of array and assigns ' new reference (note ByVal) Sub FirstDouble(ByVal array As Integer()) Dim i As Integer
12
2684
by: Andrew Bullock | last post by:
Hi, I have two classes, A and B, B takes an A as an argument in its constructor: A a1 = new A(); B b = new B(a1);
7
10395
by: AMP | last post by:
Hello, I have this in form1: namespace Pass { public partial class Form1 : Form { public Form2 form2; public Form1() {
7
3307
by: TS | last post by:
I was under the assumption that if you pass an object as a param to a method and inside that method this object is changed, the object will stay changed when returned from the method because the object is a reference type? my code is not proving that. I have a web project i created from a web service that is my object: public class ExcelService : SoapHttpClientProtocol {
0
9576
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
10175
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
10017
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
9843
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
8840
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...
0
6656
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5283
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3932
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2808
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.