473,396 Members | 1,765 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.

Class passing, to ref or not to ref...

Today I found as ignorance owe me..
Let me explain what I'm tring to do and fail (fail: in my needs)

For example, I've my stupid class:

public class Hello
{
private int x = 0;

public Hello()
{ }

public int Ics
{
get { return this.x; }
set { this.x = value; }
}
}

Perfect, now suppose, to call from a form another form and give its an
instance of our Hello class:

Hello m_hello = new Hello();
m_hello.Ics = 5;

MyForm m_frm = new MyForm();
// Assume that Data is a MyForm property type object
m_frm.Data = m_hello;
m_frm.ShowDialog(this);

Great, now from the other side, I mean the open MyForm, at OnLoad I'll
do a cast from Data to Hello than I'll modify Ics property and will
close the form WITHOUT any reassignment of Data (HIT!).

// On Load
Hello m_frmhello = (Hello)this.Data;
m_frmhello.Ics = 10;
this.Close();

On back to main form, the Hello instance (m_hello) will have the new
Ics value!! I mean will be "10".
That looks like a ref pass to Data, when it's the last thing I want.
Instead, passing to Data an object kinda int, string, bool... or a
struct, this pass will be NOT by reference. This means that Ics will
be however "5".

Can anyone can explain me why? It's cause heap and stack ? There's a
way to avoid this behave without cloning my Hello instance at the
passing moment?


Thanks one billion or maybe more ;)

Feb 6 '07 #1
9 1750
<it******@gmail.comwrote:

<snip>
Can anyone can explain me why? It's cause heap and stack ? There's a
way to avoid this behave without cloning my Hello instance at the
passing moment?
See http://pobox.com/~skeet/csharp/parameters.html
and
http://pobox.com/~skeet/csharp/memory.html

In addition, a "beta quality" article may be of some use - it's going
through a bit of peer review at the moment, and isn't finished, but you
may find it useful:

http://pobox.com/~skeet/csharp/references.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
Feb 6 '07 #2
On 6 Feb, 22:47, Jon Skeet [C# MVP] <s...@pobox.comwrote:
Seehttp://pobox.com/~skeet/csharp/parameters.html
andhttp://pobox.com/~skeet/csharp/memory.html

In addition, a "beta quality" article may be of some use - it's going
through a bit of peer review at the moment, and isn't finished, but you
may find it useful:

http://pobox.com/~skeet/csharp/references.html
<snip>

Thanks, I found first URL just few seconds ago ;)
Now start to learn...and crossing fingers resolve my problem.
Thanks
Feb 6 '07 #3
On Feb 6, 1:57 pm, "Gamon02" <itari...@gmail.comwrote:
On 6 Feb, 22:47, Jon Skeet [C# MVP] <s...@pobox.comwrote:Seehttp://pobox.com/~skeet/csharp/parameters.html
andhttp://pobox.com/~skeet/csharp/memory.html
In addition, a "beta quality" article may be of some use - it's going
through a bit of peer review at the moment, and isn't finished, but you
may find it useful:
http://pobox.com/~skeet/csharp/references.html

<snip>

Thanks, I found first URL just few seconds ago ;)
Now start to learn...and crossing fingers resolve my problem.
Thanks
I should also point out that if you search the archives of this
newsgroup, you will find many, many threads on reference types versus
value types, and pass by reference, cloning, etc.

And to answer the last question in your original post, the usual way
to solve this problem is to clone (copy) the object when you make the
method call, and pass the copy.

Feb 6 '07 #4
Bruce Wood <br*******@canada.comwrote:

<snip>
And to answer the last question in your original post, the usual way
to solve this problem is to clone (copy) the object when you make the
method call, and pass the copy.
Or to make the class act like String - make it immutable, with methods
which don't change the state of the existing instance, but which return
a new instance with changes.

--
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
Feb 7 '07 #5
On 7 Feb, 08:29, Jon Skeet [C# MVP] <s...@pobox.comwrote:
Bruce Wood <brucew...@canada.comwrote:
And to answer the last question in your original post, the usual way
to solve this problem is to clone (copy) the object when you make the
method call, and pass the copy.
Yes, is what I thought to do, but same classes are so annoying to
implement IClonable (looooong deep clone)
Or to make the class act like String - make it immutable, with methods
which don't change the state of the existing instance, but which return
a new instance with changes.

What exactly you mean for "act like String" ? How can a class do that?
Inherit to String class?

Feb 7 '07 #6
Hi,
What exactly you mean for "act like String" ? How can a class do that?
Inherit to String class?
You can overload the implicit cast operator:

class MyString
{
public string Value { get { return value; } }
private readonly string value;

public MyString(string value)
{
if (value == null)
throw new ArgumentNullException("value");

this.value = value;
}

public override int GetHashCode()
{
return value.GetHashCode();
}

public override bool Equals(object obj)
{
return value.Equals(obj);
}

public override string ToString()
{
return value;
}

public static implicit operator string(MyString myString)
{
return myString.Value;
}

public static implicit operator MyString(string str)
{
return (str == null) ? null : new MyString(str);
}
}

static void Main()
{
MyString hello = "Hello ";
string world = new MyString("World!");

Console.WriteLine("{0}{1}", hello, world);

MyString nullRef = (string) null;
Console.WriteLine(nullRef == null);
}

If you want the same properties and methods you'll have to implement them,
one by one.

--
Dave Sexton
http://davesexton.com/blog
http://www.codeplex.com/DocProject (Sandcastle in Visual Studio 2005)

"Gamon02" <it******@gmail.comwrote in message
news:11*********************@k78g2000cwa.googlegro ups.com...
On 7 Feb, 08:29, Jon Skeet [C# MVP] <s...@pobox.comwrote:
>Bruce Wood <brucew...@canada.comwrote:
And to answer the last question in your original post, the usual way
to solve this problem is to clone (copy) the object when you make the
method call, and pass the copy.

Yes, is what I thought to do, but same classes are so annoying to
implement IClonable (looooong deep clone)
>Or to make the class act like String - make it immutable, with methods
which don't change the state of the existing instance, but which return
a new instance with changes.


What exactly you mean for "act like String" ? How can a class do that?
Inherit to String class?

Feb 7 '07 #7
On Feb 7, 7:42 am, "Gamon02" <itari...@gmail.comwrote:
Or to make the class act like String - make it immutable, with methods
which don't change the state of the existing instance, but which return
a new instance with changes.

What exactly you mean for "act like String" ? How can a class do that?
Inherit to String class?
No - I only meant in terms of immutability. String is the usual
example given for an immutable class, that's all. Once you've created
a string, you can't change it. The methods which sounds like they
change it return a new one. You can implement the same kind of
behaviour yourself.

Jon

Feb 7 '07 #8
Hi,
public static implicit operator string(MyString myString)
{
return myString.Value;
}
Probably should check for null here too :)

public static implicit operator string(MyString myString)
{
return (myString == null) ? null : myString.Value;
}

--
Dave Sexton
http://davesexton.com/blog
http://www.codeplex.com/DocProject (Sandcastle in Visual Studio 2005)

"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:uk**************@TK2MSFTNGP02.phx.gbl...
Hi,
>What exactly you mean for "act like String" ? How can a class do that?
Inherit to String class?

You can overload the implicit cast operator:

class MyString
{
public string Value { get { return value; } }
private readonly string value;

public MyString(string value)
{
if (value == null)
throw new ArgumentNullException("value");

this.value = value;
}

public override int GetHashCode()
{
return value.GetHashCode();
}

public override bool Equals(object obj)
{
return value.Equals(obj);
}

public override string ToString()
{
return value;
}

public static implicit operator string(MyString myString)
{
return myString.Value;
}

public static implicit operator MyString(string str)
{
return (str == null) ? null : new MyString(str);
}
}

static void Main()
{
MyString hello = "Hello ";
string world = new MyString("World!");

Console.WriteLine("{0}{1}", hello, world);

MyString nullRef = (string) null;
Console.WriteLine(nullRef == null);
}

If you want the same properties and methods you'll have to implement them,
one by one.

--
Dave Sexton
http://davesexton.com/blog
http://www.codeplex.com/DocProject (Sandcastle in Visual Studio 2005)

"Gamon02" <it******@gmail.comwrote in message
news:11*********************@k78g2000cwa.googlegro ups.com...
>On 7 Feb, 08:29, Jon Skeet [C# MVP] <s...@pobox.comwrote:
>>Bruce Wood <brucew...@canada.comwrote:
>And to answer the last question in your original post, the usual way
to solve this problem is to clone (copy) the object when you make the
method call, and pass the copy.

Yes, is what I thought to do, but same classes are so annoying to
implement IClonable (looooong deep clone)
>>Or to make the class act like String - make it immutable, with methods
which don't change the state of the existing instance, but which return
a new instance with changes.


What exactly you mean for "act like String" ? How can a class do that?
Inherit to String class?


Feb 7 '07 #9
it******@gmail.com wrote:
Today I found as ignorance owe me..
Let me explain what I'm tring to do and fail (fail: in my needs)

For example, I've my stupid class:

public class Hello
{
private int x = 0;

public Hello()
{ }

public int Ics
{
get { return this.x; }
set { this.x = value; }
}
}

Perfect, now suppose, to call from a form another form and give its an
instance of our Hello class:

Hello m_hello = new Hello();
m_hello.Ics = 5;

MyForm m_frm = new MyForm();
// Assume that Data is a MyForm property type object
m_frm.Data = m_hello;
m_frm.ShowDialog(this);

Great, now from the other side, I mean the open MyForm, at OnLoad I'll
do a cast from Data to Hello than I'll modify Ics property and will
close the form WITHOUT any reassignment of Data (HIT!).

// On Load
Hello m_frmhello = (Hello)this.Data;
m_frmhello.Ics = 10;
this.Close();

On back to main form, the Hello instance (m_hello) will have the new
Ics value!! I mean will be "10".
That looks like a ref pass to Data, when it's the last thing I want.
Instead, passing to Data an object kinda int, string, bool... or a
struct, this pass will be NOT by reference. This means that Ics will
be however "5".

Can anyone can explain me why?
The variable m_hello contains a reference to the object you created.
What you put in the Data property is a copy of the value of the
variable. As the variable is a reference, you get a copy the reference.
It's cause heap and stack ?
Nope.
There's a
way to avoid this behave without cloning my Hello instance at the
passing moment?
Well, you don't neccesarily have to clone the instance at that precise
moment, but there is no automatic cloning of objects. If you want
another copy of your object, you have to create a copy of it.

--
Göran Andersson
_____
http://www.guffa.com
Feb 8 '07 #10

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

Similar topics

4
by: Chuck Ritzke | last post by:
I keep asking myself this question as I write class modules. What's the best/smartest/most efficient way to send a large object back and forth to a class module? For example, say I have a data...
9
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I...
6
by: Dan H. | last post by:
Hello, Is there any advantage of using a struct or a class as part of public delegate bool MyEvent(object source, SomeEventArgs e); Struct: public struct SomeEventArgs { public float...
4
by: Ron Rohrssen | last post by:
I want to show a dialog and when the form (dialog) is closed, return to the calling form. The calling form should then be able to pass the child form to another object with the form as a...
28
by: kfrost | last post by:
I know this is probably simple but I have a C# form and the class for the form is called sbaSynch. I have a textbox name txtServerName. I'm creating a class to manipulate XML functions so I...
10
by: Stan | last post by:
There are two ways to pass structured data to a web service: xml === <Order OrderId="123" OrderAmount="234" /> or class =====
12
by: scottt | last post by:
hi, I am having a little problem passing in reference of my calling class (in my ..exe)into a DLL. Both programs are C# and what I am trying to do is pass a reference to my one class into a DLL...
14
by: zon7 | last post by:
Hi, what i'm trying to do is obtaining a value from a function in a ref class. In this context I can't use the "ref" and "out" operators. I have tried all i can imagine but still hasn't it...
7
by: andy | last post by:
A question about about passing a class by reference: Say you have a class called car, and within that you have two objects called car01 and car02. Within the class I have an int variable...
3
by: notnorwegian | last post by:
i have some confusion over this. sure a class is basically a classification, like for example an animal or flower. and an object/instance of that class is then for example a cat. an object is...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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...
0
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...
0
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,...

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.