Reference on value types ?

H

Herve Bocuse

Hi,

I have a question dealing to value and reference types, boxing and unboxing.
I'm coming from the C++ world so I don't see how to do the following
feature:

I have several primitive types as members of a class. I would like to pass a
reference to these variables to somewhere else in the code and to be able to
modify the original variables from there.
So basically, how to store in a class C2 a reference to a primitive type of
another class C1 to be able to modify the primitive value from C2 ?

I understood the "ref" keyword but I can't use it because:
1. I can't store the reference. I can only use it in the called method.
2. I can't send a ref double and receive it as a ref object (because in the
receiver I want to be generic and store a reference on any value type).

Thanks a lot

Herve
 
J

Jon Skeet [C# MVP]

Herve Bocuse said:
I have a question dealing to value and reference types, boxing and unboxing.
I'm coming from the C++ world so I don't see how to do the following
feature:

I have several primitive types as members of a class. I would like to pass a
reference to these variables to somewhere else in the code and to be able to
modify the original variables from there.
So basically, how to store in a class C2 a reference to a primitive type of
another class C1 to be able to modify the primitive value from C2 ?

I understood the "ref" keyword but I can't use it because:
1. I can't store the reference. I can only use it in the called method.
2. I can't send a ref double and receive it as a ref object (because in the
receiver I want to be generic and store a reference on any value type).

You can't, basically. Now, can you tell us more about what you're
trying to do? Rather than trying to emulate what you'd do in C++, if
you tell us the general problem, we can maybe help you find out how to
approach it in C#.
 
D

Dennis Myrén

Maybe C2 should store a reference to C1 rather than C1.prop:
class C2
{
C1 c1;// or CBase cBase;
}

That way, you can use that reference to access the member field of C1.
 
H

Herve Bocuse

Thanks,

in the meantime this is the solution I put in place. But since at runtime I
have no information about C1, I must pass an object and use reflection to
find the field.

Herve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top