473,387 Members | 3,821 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,387 software developers and data experts.

How to have a reference to an object in a class?

Is it possible to put a reference to an object inside of a class? If so,
what is the syntax? The reason I want to do this is so that I can make a
copy of the original object, make modifications to the copy and then, if the
modifications are acceptable, reload the original object with the contents
of the modified copy object.

If I were doing this in C++, I'd just pass in a pointer to the original
object, copy its contents in the constructor to a temporary object, operate
on the temp object and, upon final confirmation, copy the contents of the
temp object to the original object through the passed in pointer. I'm sure
that something like this is possible in C# but I just can't get the syntax
right. How does one hang on to the original reference? I don't see how to
declare a data member as a reference. Granted, I can get around that by
doing a copy from the temp object back to the original object in the
caller's code but I want to encapsulate everything in the class and not
force the caller to do anything more than necessary.

Example:
Assume that O1 is the object that is to be modified.
Assume that C1 is the class that is responsible for handling the
modification.
When C1 is created, it gets a reference to the original O1.
The original O1 is copied into a temporary O1 inside of C1.
C1 has two possible exit conditions.
Exit successful - the contents of the modified O1 are copied to the original
O1.
Exit failure - the original O1 is left unmodified.
--
Richard Lewis Haggard
www.Haggard-And-Associates.com
Feb 5 '06 #1
11 1439
Richard Lewis Haggard wrote:
Is it possible to put a reference to an object inside of a class? If so,
what is the syntax? The reason I want to do this is so that I can make a
copy of the original object, make modifications to the copy and then, if the
modifications are acceptable, reload the original object with the contents
of the modified copy object.

If I were doing this in C++, I'd just pass in a pointer to the original
object, copy its contents in the constructor to a temporary object, operate
on the temp object and, upon final confirmation, copy the contents of the
temp object to the original object through the passed in pointer. I'm sure
that something like this is possible in C# but I just can't get the syntax
right. How does one hang on to the original reference? I don't see how to
declare a data member as a reference. Granted, I can get around that by
doing a copy from the temp object back to the original object in the
caller's code but I want to encapsulate everything in the class and not
force the caller to do anything more than necessary.

Example:
Assume that O1 is the object that is to be modified.
Assume that C1 is the class that is responsible for handling the
modification.
When C1 is created, it gets a reference to the original O1.
The original O1 is copied into a temporary O1 inside of C1.
C1 has two possible exit conditions.
Exit successful - the contents of the modified O1 are copied to the original
O1.
Exit failure - the original O1 is left unmodified.


It sounds me that you want to look into implementing the clone method in
IClone.

John
Feb 5 '06 #2
Using "ref" should do it, as in the following example.

class Exec
{
static void Main()
{
MyClass m = new MyClass();
MyObject ob = new MyObject();
ob.gem = 1;
bool changed = m.ChangeObj(ref ob);
Console.WriteLine("ob.gem = {0}", ob.gem);
}
}
class MyClass
{
// returns true if the original object is changed
public bool ChangeObj( ref MyObject o)
{
o.gem++; // change the object
if (o.gem > 1) // made-up criterion
{
o.gem--; // restore object
return false;
}
else
return true;
}
}
class MyObject
{
public int gem;
private int sowsEar;
}

Cheers,
Tech Dr.

Feb 5 '06 #3
Tech Dr. <te*****@earthlink.net> wrote:
Using "ref" should do it, as in the following example.


I think you've misunderstood the purpose of "ref". Nothing in your
example requires the use of ref.

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
Feb 5 '06 #4
Jon is quite right. Apologies. It seems that the example will do what
you need (?) without "ref."

Feb 5 '06 #5
Tech Dr. <te*****@earthlink.net> wrote:
Jon is quite right. Apologies. It seems that the example will do what
you need (?) without "ref."


It's not quite clear to me exactly what the OP needs - hopefully the
other posts in the thread will have helped though.

--
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 5 '06 #6
Jon Skeet [C# MVP] wrote:
I think he wants to implement some kind of deep copy.
Tech Dr. <te*****@earthlink.net> wrote:
Jon is quite right. Apologies. It seems that the example will do what
you need (?) without "ref."


It's not quite clear to me exactly what the OP needs - hopefully the
other posts in the thread will have helped though.

Feb 5 '06 #7
"Richard Lewis Haggard" <HaggardAtWorldDotStdDotCom> wrote in message
news:Og*************@TK2MSFTNGP11.phx.gbl...
Is it possible to put a reference to an object inside of a class?


I think I understand your design objectives, so let me describe it back to you.

You wish to maintain a sort or transactional consistency in the face of possible exceptions.
For instance:
you need to perform Task2, Task2 and Task3 on your object and you need ALL of them to succeed.
If any of them fail you want your object to remain unchanged.
So you want to Copy the original (Clone)
Perform all of the Tasks on the Clone.
If successful Copy the changes back to the original in an exception safe way.

If you NEED to REPLACE the original object with the modified version it is tricky.
If you need to UPDATE the original object it is easy.

I will demonstrate the UPDATE mechanism (If you need the Other Mechanism, I can deal with that
later)

public class C1
{
private O1 = myO1;
public C1(O1 myO1)
{
this.myO1 = myO1;
}

public bool Modify()
{
// Clone myO1
// do horrible and unspeakable things to the clone
// if the clone survives update myO1 with the changes.
// I assume the Update operation is exception safe (copy a reference or 2)
myO1.Update(myclone);

//return success/failure
}
}
If this doesn't suit your needs, let me know
Bill
Feb 5 '06 #8
I understand the ref keyword. What I wanted to do was to make it possible
for the called function to replace the passed in argument without forcing
the caller to do the deep copy. I'd wanted to pass the object in on the
constructor. Since it doesn't appear to be possible to keep a reference as a
data member, I reworked the logic and made it work the way that I wanted
which was:

Call a function.
Make a copy of an input object.
Modify the copied object in multiple steps.
If the user cancels out of the modification operation at any point in the
process, leave the original object unchanged.
Otherwise, if the modification process runs to completion then replace the
original object with the modified object.

I did what I needed but just couldn't use a class data member that was a
reference to the original object. 'Nuff said.
--
Richard Lewis Haggard
www.Haggard-And-Associates.comx
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Tech Dr. <te*****@earthlink.net> wrote:
Using "ref" should do it, as in the following example.


I think you've misunderstood the purpose of "ref". Nothing in your
example requires the use of ref.

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

Feb 6 '06 #9
Richard Lewis Haggard wrote:
I understand the ref keyword. What I wanted to do was to make it possible
for the called function to replace the passed in argument without forcing
the caller to do the deep copy. I'd wanted to pass the object in on the
constructor. Since it doesn't appear to be possible to keep a reference as a
data member
Either you're misunderstanding something or you're using the incorrect
terminology. Assuming the type you're dealing with is a reference type,
a reference is *exactly* what you keep as a data member. However, it's
a reference to an object, not a reference to a variable.
I reworked the logic and made it work the way that I wanted
which was:

Call a function.
Make a copy of an input object.
Modify the copied object in multiple steps.
If the user cancels out of the modification operation at any point in the
process, leave the original object unchanged.
Otherwise, if the modification process runs to completion then replace the
original object with the modified object.

I did what I needed but just couldn't use a class data member that was a
reference to the original object. 'Nuff said.


Not really - by default you *will get* a reference to the original
object. I *think* you're using "object" when you mean "variable", given
everything else you've said. However, it's still not entirely clear to
me. Perhaps you could give an example using something we all know
about, such as ArrayList or StringBuilder?

Jon

Feb 6 '06 #10
This may not be worth pursuing since I worked around it, but what I wanted
to do was to declare a data member in Class2 to be a reference to a Class1
and to assign this reference member from an input argument during the Class2
construction. I couldn't figure out how to do it without generating a
compiler build time error.

I don't have that particular piece of code available to me right this second
but it would have been similar to the below:

// Class to be referenced.
public Class1
{
}

// Class to contain the reference to Class1.
public Class2
{
private ref Class1 m_refClass1;

public Class2( ref Class1 class1)
{
m_refClass1 = class1;
}
}

Build fails.

--
Richard Lewis Haggard
www.Haggard-And-Associates.com
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Richard Lewis Haggard wrote:
I understand the ref keyword. What I wanted to do was to make it possible
for the called function to replace the passed in argument without forcing
the caller to do the deep copy. I'd wanted to pass the object in on the
constructor. Since it doesn't appear to be possible to keep a reference
as a
data member


Either you're misunderstanding something or you're using the incorrect
terminology. Assuming the type you're dealing with is a reference type,
a reference is *exactly* what you keep as a data member. However, it's
a reference to an object, not a reference to a variable.
I reworked the logic and made it work the way that I wanted
which was:

Call a function.
Make a copy of an input object.
Modify the copied object in multiple steps.
If the user cancels out of the modification operation at any point in the
process, leave the original object unchanged.
Otherwise, if the modification process runs to completion then replace
the
original object with the modified object.

I did what I needed but just couldn't use a class data member that was a
reference to the original object. 'Nuff said.


Not really - by default you *will get* a reference to the original
object. I *think* you're using "object" when you mean "variable", given
everything else you've said. However, it's still not entirely clear to
me. Perhaps you could give an example using something we all know
about, such as ArrayList or StringBuilder?

Jon

Feb 6 '06 #11
<"Richard Lewis Haggard" <HaggardAtWorldDotStdDotCom>> wrote:
This may not be worth pursuing since I worked around it, but what I wanted
to do was to declare a data member in Class2 to be a reference to a Class1
and to assign this reference member from an input argument during the Class2
construction. I couldn't figure out how to do it without generating a
compiler build time error.

I don't have that particular piece of code available to me right this second
but it would have been similar to the below:

// Class to be referenced.
public Class1
{
}

// Class to contain the reference to Class1.
public Class2
{
private ref Class1 m_refClass1;

public Class2( ref Class1 class1)
{
m_refClass1 = class1;
}
}


If that were possible, m_refClass1 wouldn't be a reference to an
instance of Class2 - it would be a reference to a *variable* of type
Class2. That's what I meant before. If you just declare:

private Class1 m_refClass1;

then m_refClass1 is a reference to an instance of Class1 (or null). The
value of a variable like m_refClass1 or class1 is always a reference,
never an object.

It's quite an important distinction to make.

--
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 '06 #12

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

Similar topics

2
by: Ryan Hubbard | last post by:
I would like to use a static variable inside a method in an object to hold a reference to another object. But i can't get it to work. Here is an example class B{ var $test; } class A{...
1
by: lawrence | last post by:
The following class method is being rejected by the PHP parser. If I change the method paramaters and allow the objects to be passed as copies, then the parser has no problem. Or, if I pass by...
3
by: klaas | last post by:
the following code gives rise to the beneath error message, only when a matrix object is instantiated as matrix<bool>, not with matrix<float>: /*returns a reference to the object at position...
2
by: Agent Mulder | last post by:
Hi group, I try to get a reference to a template. In the template, a virtual function is declared. Later in the program, I inherit from classes created by the template. So the template is the...
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
4
by: Jeff | last post by:
The derived class below passes a reference to an object in its own class to its base calss constructor. The code compiles and will run successfully as long as the base class constructor does not...
3
by: Ganesh Palaniappan | last post by:
We're getting following exception for the below piece of code. We're wondering how it is possible since we're having a null check for objGraphics and strokePen... Exception:...
10
by: subramanian100in | last post by:
Consider the following code: #include <iostream> #include <cstdlib> using namespace std; int main() { const double& ref = 100;
275
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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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
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...

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.