473,802 Members | 2,413 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reference Types and Value Types

This is a pretty basic-level question, but I'd really like to know, so
thanks for any help or pointers you can provide (like what I would
google for ;o)

Suppose:

<code>

myFunc()
{
SomeType myType = new SomeType;
Console.Write(m yType.MyPropert y);
bool whatever = myOtherFunc(myT ype);
}

myOtherfunc(Som eType passedType)
{
Console.Write(m yType.ToString( ))
return true;
}

</code>

My question: since myType is a reference type, only one instance of this
object is ever created in memory, right? The Lead Software Architect
here (C++, no C# experience) was telling me about passing by reference--
is this implicitly done by reference types in C#? Also, could I pass by
value? Why would I want to?

All these questions are asked under the auspices of least amount of
overhead. My primary concern is good coding practices (and learning).

Thank you,
-daniel
Nov 16 '05 #1
19 2146
daniel,
To my knowledge you can't pass a "reference" type by value if you wanted
to. It is automatically passed by reference. If you have a value type and
you want to maintain it's value across method calls, you need to pass it by
reference.

example should print out 12:

private void Test()
{
int index = 0;
Test2(ref index);
Console.Write(i ndex.ToString() );
}

private void Test2(ref index)
{
index = 12;
}

--
Lateralus [MCAD]
"daniel" <us**@example.c om> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..
This is a pretty basic-level question, but I'd really like to know, so
thanks for any help or pointers you can provide (like what I would google
for ;o)

Suppose:

<code>

myFunc()
{
SomeType myType = new SomeType;
Console.Write(m yType.MyPropert y);
bool whatever = myOtherFunc(myT ype);
}

myOtherfunc(Som eType passedType)
{
Console.Write(m yType.ToString( ))
return true;
}

</code>

My question: since myType is a reference type, only one instance of this
object is ever created in memory, right? The Lead Software Architect here
(C++, no C# experience) was telling me about passing by reference--
is this implicitly done by reference types in C#? Also, could I pass by
value? Why would I want to?

All these questions are asked under the auspices of least amount of
overhead. My primary concern is good coding practices (and learning).

Thank you,
-daniel

Nov 16 '05 #2
Ahh, thank you Lateralus for the quick reply. I have a quick follow up
question, though:

If a reference type is always passed by reference, then (while stupid
and messy):

<code>
// with a return type this time!
void func1()
{
SomeType myType = new myType();
func2(myType);
}
void func2(SomeType myType)
{
func3(mytype);
}
void func3(SomeType myType)
{
Console.Write(m yType.ToString( ));
}
</code>

will not cause a substantial amount of increased overhead at all (other
than variables on the stack), because only one object is every created.
Thanks,
-daniel

Lateralus [MCAD] wrote:
daniel,
To my knowledge you can't pass a "reference" type by value if you wanted
to. It is automatically passed by reference. If you have a value type and
you want to maintain it's value across method calls, you need to pass it by
reference.

example should print out 12:

private void Test()
{
int index = 0;
Test2(ref index);
Console.Write(i ndex.ToString() );
}

private void Test2(ref index)
{
index = 12;
}

Nov 16 '05 #3
Daniel,
For information on reference types & value types along with passing by value
& passing by reference see:

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

Hope this helps
Jay

"daniel" <us**@example.c om> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..
This is a pretty basic-level question, but I'd really like to know, so
thanks for any help or pointers you can provide (like what I would google
for ;o)

Suppose:

<code>

myFunc()
{
SomeType myType = new SomeType;
Console.Write(m yType.MyPropert y);
bool whatever = myOtherFunc(myT ype);
}

myOtherfunc(Som eType passedType)
{
Console.Write(m yType.ToString( ))
return true;
}

</code>

My question: since myType is a reference type, only one instance of this
object is ever created in memory, right? The Lead Software Architect here
(C++, no C# experience) was telling me about passing by reference--
is this implicitly done by reference types in C#? Also, could I pass by
value? Why would I want to?

All these questions are asked under the auspices of least amount of
overhead. My primary concern is good coding practices (and learning).

Thank you,
-daniel

Nov 16 '05 #4
daniel,
That is correct. There is only one storage location of the object. The
variables all just point to the same object.

--
Lateralus [MCAD]
"daniel" <us**@example.c om> wrote in message
news:Of******** ******@TK2MSFTN GP11.phx.gbl...
Ahh, thank you Lateralus for the quick reply. I have a quick follow up
question, though:

If a reference type is always passed by reference, then (while stupid and
messy):

<code>
// with a return type this time!
void func1()
{
SomeType myType = new myType();
func2(myType);
}
void func2(SomeType myType)
{
func3(mytype);
}
void func3(SomeType myType)
{
Console.Write(m yType.ToString( ));
}
</code>

will not cause a substantial amount of increased overhead at all (other
than variables on the stack), because only one object is every created.
Thanks,
-daniel

Lateralus [MCAD] wrote:
daniel,
To my knowledge you can't pass a "reference" type by value if you
wanted to. It is automatically passed by reference. If you have a value
type and you want to maintain it's value across method calls, you need to
pass it by reference.

example should print out 12:

private void Test()
{
int index = 0;
Test2(ref index);
Console.Write(i ndex.ToString() );
}

private void Test2(ref index)
{
index = 12;
}

Nov 16 '05 #5
Daniel.... By default all parameters in C# are passed by value, but you
cannot
pass an actual object as a parameter. You can only a pass a reference
to an
object as a parameter. So, by default, in C# you actually pass a
reference by
value as a parameter. This is very confusing to C++ coders who assume
this
is the equivalent of C++ pass by reference. It is not. Although the
behavior is
_similar_ to C++ pass by reference, it is not identical. So C++ coders
need to
understand first that although objects use value semantics in C++,
objects in
C# use reference semantics. For instance, RefVariableA= RefVariableB
does
not call a copy constructor in C#, it simply assigns RefVariableA to
"point" to
the same object "pointed" to by RefVariableB. In C#, you pass a
reference to
an an object by value so that a copy of the reference goes on the stack.
The
object is not copied. You can touch and modify the object using the
reference
within the method, but if you reassign the reference within the method
there
are no side effects outside of the method. Of course, this does not
apply if
you override the default behaviour and explicitly pass a parameter by
reference. So to summarize, since objects in C++ use value semantics and
objects in C# use reference semantics, the concept of "pass by
reference" has
a very different meaning in C++ and C#.

Regards,
Jeff
My question: since myType is a reference type, only one instance of

this
object is ever created in memory, right? The Lead Software Architect
here (C++, no C# experience) was telling me about passing by reference--
is this implicitly done by reference types in C#? Also, could I pass by
value?<

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #6
Thank you Lateralus, Jay and Jeff.
Nov 16 '05 #7
<"Lateralus [MCAD]" <dnorm252_at_ya hoo.com>> wrote:
To my knowledge you can't pass a "reference" type by value if you wanted
to. It is automatically passed by reference.


No. The reference is passed by value, which is quite different.

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

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
You can't pass by value in C#, not unless the type is a value type, like
something that is declared 'struct' rather than 'class', or a basic variable
like int, byte etc.
There's no reason why you'd want to, if you did, then that'd be tantamount
to trying to do the garbage collector's work for it, and it was designed to
be global and operate off its own bat.
So just don't bother about the memory - just make it as OO as possible.

"daniel" wrote:
This is a pretty basic-level question, but I'd really like to know, so
thanks for any help or pointers you can provide (like what I would
google for ;o)

Suppose:

<code>

myFunc()
{
SomeType myType = new SomeType;
Console.Write(m yType.MyPropert y);
bool whatever = myOtherFunc(myT ype);
}

myOtherfunc(Som eType passedType)
{
Console.Write(m yType.ToString( ))
return true;
}

</code>

My question: since myType is a reference type, only one instance of this
object is ever created in memory, right? The Lead Software Architect
here (C++, no C# experience) was telling me about passing by reference--
is this implicitly done by reference types in C#? Also, could I pass by
value? Why would I want to?

All these questions are asked under the auspices of least amount of
overhead. My primary concern is good coding practices (and learning).

Thank you,
-daniel

Nov 16 '05 #9
Patty O'Dors <Pa********@dis cussions.micros oft.com> wrote:
You can't pass by value in C#, not unless the type is a value type, like
something that is declared 'struct' rather than 'class', or a basic variable
like int, byte etc.


Not true. Everything is passed by value by default - whether the value
is a struct or a reference. You can't pass an actual *object* either by
reference or by value.

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

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

Similar topics

13
17936
by: Abe Frohnman | last post by:
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
5
1554
by: Javier Campos | last post by:
WARNING: This is an HTML post, for the sake of readability, if your client can see HTML posts, do it, it doesn't contain any script or virus :-) I can reformat a non-HTML post if you want me to (and if this doesn't see correctly with non-HTML viewers) Ok, I'm fed up with this so I'll explain the situation here and my approach (which sucks), and see if anyone can give a better solution to this. I'm making a way to have several parameters...
13
2799
by: Maxim | last post by:
Hi! A have a string variable (which is a reference type). Now I define my Method like that: void MakeFullName(string sNamePrivate) { sNamePrivate+="Gates" }
12
2689
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);
9
1894
by: Edward Diener | last post by:
Can one use 'ref' ( or 'out' ) on a reference type to create a reference to a reference in C#. I know one can use it on a value type to create a reference to that value.
27
3134
by: Terry | last post by:
I am getting the following warning for the below function. I understand what it means but how do I handle a null reference? Then how do I pass the resulting value? Regards Warning 1 Function 'Dec2hms' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
10
13666
by: Robert Dailey | last post by:
Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the function is also modified. Sometimes I wish to work with "copies", in that when I pass in an integer variable into a function, I want the function to be modifying a COPY, not the reference. Is this possible?
1
1841
by: az.anonymous | last post by:
Im starting to learn C#, and I made a simple stack class. Inside the stack class I had the following: class StackElement { object info; StackElement below; } Everything works fine cause "below" is just a reference. But, what if
275
12420
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
9699
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
10535
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
10303
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
9111
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
6838
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
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
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
2
3792
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2966
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.