473,466 Members | 4,869 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

ValueType reference in objects

Hi all,

With the followin code:

class MyClass
{
public int i;
public MyClass(ref int I)
{
i = I;
}
}

class Program
{
static void Main(string[] args)
{
int i = 50;
MyClass c = new MyClass(ref i);
Console.WriteLine(c.i);

i = 10;
Console.WriteLine(c.i);

Console.ReadLine();
}
}

I´ve got:

50
50

The i field from c object didn´t change its value.
The i field doesn´t point to i address.

C# copies the value from the i variable to the object heap field i.
Is this correct? Heap object doesn´t point to stack variables?

Please help.

TIA,

--
Andre Azevedo

Nov 22 '06 #1
8 1250
"Andre Azevedo" <Andre Az*****@discussions.microsoft.comwrote in message
news:6C**********************************@microsof t.com...
C# copies the value from the i variable to the object heap field i.
Is this correct? Heap object doesn´t point to stack variables?
No, it doesn't. There might be a way to generate a reference to a local
variable, but if there is I don't know what it is, and for sure the code you
posted doesn't. Except, of course, as the "by reference" parameter in the
constructor...but in that case, you still can't access the reference
directly, it just means that if you change the value of the parameter in the
constructor, the original variable passed in is changed as well. That
behavior does not extend to other values to which the parameter is assigned.

Pete
Nov 22 '06 #2
Hey Andre...
public MyClass(ref int I)
{
i = I;
}
... SNIP ...
C# copies the value from the i variable to the object heap field i.
Is this correct? Heap object doesn´t point to stack variables?
Value of I is copied to the location of i. Indeed, since MyClass is a
class, its memory is allocated on the heap. But because i is int, a
value type, the "=" operator copies its content, and does not assign
it's location (address).

Note: This is true for strings too, although they are reference types.
The "=" operator for strings is implemented to behave like a the
assignment of a value type.

Does this answer your question?

David
Nov 22 '06 #3
Hey

You could try creating a custom integer class and pass it to the your
cons instead of int
Peter Duniho wrote:
"Andre Azevedo" <Andre Az*****@discussions.microsoft.comwrote in message
news:6C**********************************@microsof t.com...
C# copies the value from the i variable to the object heap field i.
Is this correct? Heap object doesn´t point to stack variables?

No, it doesn't. There might be a way to generate a reference to a local
variable, but if there is I don't know what it is, and for sure the code you
posted doesn't. Except, of course, as the "by reference" parameter in the
constructor...but in that case, you still can't access the reference
directly, it just means that if you change the value of the parameter in the
constructor, the original variable passed in is changed as well. That
behavior does not extend to other values to which the parameter is assigned.

Pete
Nov 22 '06 #4
If your goal is to simply find a way to pass in integer pointers, then the
following code will work. I would like to point out that using pointers and
unsafe code is NOT recommended and should be reserved for special case
scenarioes.

You will also need to check the "Allow unsafe code" option in the Build tab
of your project properties.

unsafe class MyClass
{
public int* i;
public MyClass(int* I)
{
i = I;
}
}

class Program
{
unsafe static void Main(string[] args)
{
int i = 50;
MyClass c = new MyClass(&i);
Console.WriteLine(*c.i);

i = 10;
Console.WriteLine(*c.i);

Console.ReadLine();
}
}

HTH :-)
--
Good luck!

Shailen Sukul
Architect
(BSc MCTS, MCSD.Net MCSD MCAD)
Ashlen Consulting Service P/L
(http://www.ashlen.net.au)
"Andre Azevedo" wrote:
Hi all,

With the followin code:

class MyClass
{
public int i;
public MyClass(ref int I)
{
i = I;
}
}

class Program
{
static void Main(string[] args)
{
int i = 50;
MyClass c = new MyClass(ref i);
Console.WriteLine(c.i);

i = 10;
Console.WriteLine(c.i);

Console.ReadLine();
}
}

I´ve got:

50
50

The i field from c object didn´t change its value.
The i field doesn´t point to i address.

C# copies the value from the i variable to the object heap field i.
Is this correct? Heap object doesn´t point to stack variables?

Please help.

TIA,

--
Andre Azevedo
Nov 22 '06 #5
Yes.
Thanks!

"David Boucherie & Co" <da*************@telenet.bewrote in message
news:Od**************@TK2MSFTNGP02.phx.gbl...
Hey Andre...
> public MyClass(ref int I)
{
i = I;
}
... SNIP ...
C# copies the value from the i variable to the object heap field i.
Is this correct? Heap object doesn´t point to stack variables?

Value of I is copied to the location of i. Indeed, since MyClass is a
class, its memory is allocated on the heap. But because i is int, a value
type, the "=" operator copies its content, and does not assign it's
location (address).

Note: This is true for strings too, although they are reference types. The
"=" operator for strings is implemented to behave like a the assignment of
a value type.

Does this answer your question?

David

Nov 22 '06 #6
Hi,

I just ask because I really didn't know what happens with my code.
I have a thread that polls hardware events in a loop calling an unmanaged
function. The event structure has unions with value and reference types and
to receive the event structure I use IntPtr: (non-blittable)

For instance:

int eventSize = 0;
IntPtr event;

while(threadActive)
{

event = Marshal.AllocHGlobal(256);

int result = StaticClass.UnmanagedFunction(IntPtr event, ref eventSize);
....
(parse IntPtr)
...

Marshal.FreeHGlobal(event);

}

Now, I want to parse the event variable asynchronously. So I have to
encapsulate it in some class and this class is passe in
ThreadPool.QueueUserWorkItem method:

{
....
event = Marshal.AllocHGlobal(256);
int result = StaticClass.UnmanagedFunction(IntPtr event, ref eventSize);

MyContainerClass c = new MyContainerClass(ref IntPtr); <----- What happes
here!
ThreadPool.QueueUserWorkItem(new WaitCallback(MyWaitCallBackMethod),
MyContainerClass);
....
}

void MyWaitCallBackMethod(object state)
{

MyContainerClass c = (MyContainerClass) state;
IntPtr event = c.event;
...
(parse IntPtr)
...
Marshal.FreeHGlobal(event);

}

That's why I ask about "ref" value parameters.
Thanks!

--
Andre Azevedo
"Shailen Sukul" <sh***@ashlen.net.auwrote in message
news:CE**********************************@microsof t.com...
If your goal is to simply find a way to pass in integer pointers, then the
following code will work. I would like to point out that using pointers
and
unsafe code is NOT recommended and should be reserved for special case
scenarioes.

You will also need to check the "Allow unsafe code" option in the Build
tab
of your project properties.

unsafe class MyClass
{
public int* i;
public MyClass(int* I)
{
i = I;
}
}

class Program
{
unsafe static void Main(string[] args)
{
int i = 50;
MyClass c = new MyClass(&i);
Console.WriteLine(*c.i);

i = 10;
Console.WriteLine(*c.i);

Console.ReadLine();
}
}

HTH :-)
--
Good luck!

Shailen Sukul
Architect
(BSc MCTS, MCSD.Net MCSD MCAD)
Ashlen Consulting Service P/L
(http://www.ashlen.net.au)
"Andre Azevedo" wrote:
>Hi all,

With the followin code:

class MyClass
{
public int i;
public MyClass(ref int I)
{
i = I;
}
}

class Program
{
static void Main(string[] args)
{
int i = 50;
MyClass c = new MyClass(ref i);
Console.WriteLine(c.i);

i = 10;
Console.WriteLine(c.i);

Console.ReadLine();
}
}

I´ve got:

50
50

The i field from c object didn´t change its value.
The i field doesn´t point to i address.

C# copies the value from the i variable to the object heap field i.
Is this correct? Heap object doesn´t point to stack variables?

Please help.

TIA,

--
Andre Azevedo

Nov 23 '06 #7
David Boucherie & Co <da*************@telenet.bewrote:
Note: This is true for strings too, although they are reference types.
The "=" operator for strings is implemented to behave like a the
assignment of a value type.
There's nothing special about how "=" is handled with strings. It's the
same as with every other reference type - it just copies the reference.

Strings just happen to be immutable, so things like Replace return a
reference to a new string, and if you do:

x += "fred";

that is the same as:

x = x + "fred";

where x + "fred" returns a new string which is the concatenation of x
and "fred".

Nothing special at all in there. Note that in fact you can't overload
the "=" operator in C# (fortunately, IMO).

--
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
Nov 23 '06 #8
Andre Azevedo <xp**@xpto.comwrote:

<snip>
That's why I ask about "ref" value parameters.
"ref" only makes a difference if you change the *parameter* during the
method. Other than that, it behaves just like any other parameter. In
particular:

myVariable = myParameter;

is just a copy of the value of myParameter to myVariable, whether the
myParameter parameter is passed by reference or not. There's no "link"
forged between myVariable and myParameter.

See http://www.pobox.com/~skeet/csharp/parameters.html for more on
parameter passing.

--
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
Nov 23 '06 #9

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

Similar topics

4
by: Shawn B. | last post by:
Greetings, I know I can create class that "implicit"ly accepts an 8-bit to 64-bit value. Without using double, or single, I would like to create my own "unsigned" 128-bit valuetype (to be used...
4
by: Brian Brane | last post by:
I have properties that wrap DataRow columns as in: public int aNumber { get{ return m_DataRow; } set{ m_DataRow = value; } } If the column happens to contain DBNull, I get a cast exception...
2
by: Eric Newton | last post by:
Since String.Format has to box all value types to accomodate the params, and just for sheer efficiency, are there possibly any plans for a FormatValue method to minimize boxing? public static...
6
by: Sahil Malik | last post by:
Okay, I can't inherit from System.ValueType. Why this restriction?? What I am trying to acheive is, create my own ValueType called "Money". So if I have a decimal that has value 1.93991, when...
6
by: Aryeh Holzer | last post by:
Let me start with a quote from the C# Programmers Reference (where I learned the cool word "covariance"): "When a delegate method has a return type that is more derived than the delegate...
1
by: INeedADip | last post by:
PropertyInfo props = obj.GetType().GetProperties(); foreach (PropertyInfo p in props) if (p.PropertyType is ValueType) this._commonProperties.Add(p.Name, p.GetValue(request, null).ToString()); ...
6
by: Manikkoth | last post by:
Hello, Just curious to see why ValueType (which the base for all value types) is a class. I thought "class" would make a type a reference type. However, IsValueType for ValueType is returning...
1
by: Tony Johansson | last post by:
Hello! Everything not derived from System.ValueType is a reference type. I just wonder this ValueType type is derived from Object and it overrides the two methods Equals and GetHashCode which...
2
by: Veeranna Ronad | last post by:
Hello, Our application gets datetime from an interface function. This function returns "ValueType". How to copy datetime content from this "ValueType" to DateTime variable? Thanks in advance...
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
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...
1
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
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 ...

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.