P
PGP
How do i pass a const object to a function in C#?
I mean the equivalent of
void Func(const MyObject obj)
{
}
I mean the equivalent of
void Func(const MyObject obj)
{
}
How do i pass a const object to a function in C#? I mean the equivalent of
void Func(const MyObject obj)
{
}
void Func(const MyObject obj)
{
}
All objects are passed by reference by default. Please elaborate if i missedLarry Smith said:There is no analogue for this in C# AFAIK (a significant language
short-coming IMO). BTW, you should be passing by reference in your call
above (or by pointer but a reference is arguably better for "const"
objects).
void Func(const MyObject obj)
{
}
Larry Smith said:All objects are passed by reference by default. Please elaborate if i
missed anything.
PeterPeter Duniho said:I don't understand Larry's comment either (the application of "const" in
C++ depends on whether something is passed by value or by reference, but
it's useful in both scenarios), but it's not true that "all objects are
passed by reference by default". How something is passed to a method
depends on the _argument_, not the object. And only arguments declared
with "ref" or "out" are passed "by reference". Otherwise, they are passed
"by value".
When passing a reference type by value, it's true that a reference is the
value that's passed. But the _passing_ itself is "by value".
Pete
Peter said:Not sure what you mean here. A reference type in C# passed by value
is most like passing a pointer in C++ (for example, to a method with a
declaration like "void method(char *pch)", in which a reference to a
char is passed by value). Passing by reference in C++ ("void
method(char &psz)") is just like passing by reference in C#.
That's not true, and your mistake is the crux of my point. You can in
fact pass a reference type by value in C#, and what you get is the
reference. That's what the value of a reference type is.
Peter Duniho said:[...]That's not true, and your mistake is the crux of my point. You can in
fact pass a reference type by value in C#, and what you get is the
reference. That's what the value of a reference type is.
Which is just another way of saying you never pass the content of a
reference type by value, you can only pass the value of a tracking
handle to the data. There is NO way of getting rid of the indirection.
True. That's what it means for something to be a reference type. The
type is the _reference_ to the object, not the object itself.
But that doesn't change the fact that there's a difference between passing
a reference type by value and a reference type by reference (or a value
type by reference, for that matter).