Steve Jackson

I remember from a couple of the C++ courses that I have taken that (in C++) you can pass a parameter by reference, but set it as readonly. I sort of remember it being ' const byref ' but I may be wrong - the concept is what is important. Doing this is supposed to improve performance because it only passes the pointer to the parameter, not the entire parameter. The readonly aspect, though, kept it safe from being inadvertantly changed by the method.

The reason that I ask is that I am passing a couple of large objects in my c# program, and wondered there was something equivelant in c#. My suspicion is that the compiler takes care of it, but I wanted to be sure.

Thanks,

SteveJ




Re: Visual C# General Passing parameter as byref, readonly

Steve Py

In C++ it was done using the const modifier, but unfortunately in C# there is no support for constant references. Reference type variables can be modified by called code.






Re: Visual C# General Passing parameter as byref, readonly

Coops66

This is the default behaviour in C#. Passing a reference type as a parameter is only passing the reference/pointer to the object. If you omit the "ref" keyword in the parameter list then the method can't change the reference to point to another object of the same type. I'm assuming that you want the method to access the methods and properties of your large objects rather than have the object as readonly which you have control of in the property accessor declarations.





Re: Visual C# General Passing parameter as byref, readonly

Steve Jackson

Thanks, both of you for the reply.

When you, Coops66, say that this is the default behavior for C#, is this true for passing byval and byref

Thanks,

SteveJ






Re: Visual C# General Passing parameter as byref, readonly

Peter Ritchie

Value types (structs) are passed by value and reference types (classes) are passed by reference (i.e. you can't pass a reference type by value). When you add the "ref" or "out" keyword to a parameter you're really saying pass the reference by reference, in the case of classes. "ref" on a value type works as you've described for C++.






Re: Visual C# General Passing parameter as byref, readonly

Sean Fowler

This question is similar to this thread. If you check my last post it should hopefully help to make it clearer.

Sean






Re: Visual C# General Passing parameter as byref, readonly

Steve Jackson

Thanks a lot Sean, Peter, et. all;

I appreciate your willingness to answer these types of questions. I realize that it must get old afterwhile. For whatever reason, these are aspects of the language that I haven't been able to find well explained in the C# books that I have.

Thanks again,

SteveJ