How to pass a const struct by reference

G

Guest

I have a huge struct with many members.I don't want to copy
this struct to the stack, that's why i pass it by reference to
a function. But also i want the function to be unable to modify it.
Something like that in C++:

bool func( const Str& myStr )
{
....
}
 
J

Jeff Louie

I don't know if this is want you want, but you can box a structure. int
maps to struct Int32.

int i= 1; // value semantics
object o= i; // reference semantics

Regards,
Jeff
 
J

Jon Skeet [C# MVP]

Alexander Kolev said:
I have a huge struct with many members.I don't want to copy
this struct to the stack, that's why i pass it by reference to
a function. But also i want the function to be unable to modify it.
Something like that in C++:

bool func( const Str& myStr )
{
....
}

I'd first check whether you really need it to be a struct - is there
any particular reason for it being a value type in the first place?
Usually things with lots of members aren't good candidates for being
value types.
 
J

Jeff Louie

Alexander... I was too busy to give any lengthy answer earlier. There is
no
equivalent of that use of C++ const in C#. The general solution is store
the
data in a read write collection and then wrap a reference to the
collection in a
read only class using containment by reference. You can then pass a
reference to the read only class to the client. In this manner only one
copy of
the collection exists. A smarty solution is to derive a read write class
from a
read only class, create an instance of the read write class and pass a
reference to the read only base class. This is not foolproof since the
client can
still cast the reference to the actual read write class much as you can
const_cast in C++.

In C++ both struct and classes have value semantics. In C# structs have
value
semantics and classes have reference semantics. If you store a struct in
most
C# collections they get boxed anyway, so in general, classes are favored
over
structs.

Regards,
Jeff
 

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