tags:

views:

90

answers:

3

If you create a class in .NET, is there any way to place a restriction on it so that if it's passed into some method (as an input parameter), then it can only be passed by reference or only passed by value?
I was thinking maybe via a attribute on the class?

A: 
  • Class are always passed by reference.
  • Struct are "always" passed by value. (but there are ways to get around that)
James Curran
-1: You're confusing the thing you pass with how you pass it. An object reference can be passed by value or by reference. It is a *reference type* however. And by default, it is passed by value. That is, you're passing a reference by value, which refers to a reference type.
Lasse V. Karlsen
This answer is incorrect, Lasse is absolutely right. Go read [Jon Skeet's article on parameter passing](http://www.yoda.arachsys.com/csharp/parameters.html) I kindly suggest.
Noldorin
A: 

I'm not sure what you are trying to achieve, but can you use struct rather than class for the type that you don't user to pass by reference? Struct is ValueType as defined by the CLR.

Fadrian Sudaman
+1  A: 

I believe the answer is no because ByVal and ByRef are choices made by the method, not the caller or the type designer.

However, it sounds like what you want is to create a type that you know will be immutable? Maybe you want to be sure it will NEVER be changed? Then what you can do is one of the following (not a complete list):

Create the object so that you have access to the settable properties through use of private, public, internal keywords etc.

Create the object so that the only way you can get at it's internal state is via the constructor.

Implement an interface and pass around that interface instead of the objects that implement it. The interface would be designed to only read the internal state of the object.

Prevent anyone from deriving from the object with the sealed (C#) or NotInheritable (VB) keywords.

Chris Gomez
Thanks for all your replies.Yes, I was mainly talking about passing a reference type, and restricting it to being passed by reference only.It basically gets passed in to(and used by) several methods. IE: MethodA gets the object; eventually passes it to MethodB; which eventually passes it to MethodC, etc. I guess I wanted to make sure that each reference points to the same, original object.
imcatalyst