views:

1899

answers:

4

I want to pass a reference type by value to a method in C#. Is there a way to do it.

In C++, I could always rely on the copy constructor to come into play if I wanted to pass by Value. Is there any way in C# except: 1. Explicitly creating a new object 2. Implementing IClonable and then calling Clone method.

Here's a small example:

Let's take a class A in C++ which implements a copy constructor.

A method func1(Class a), I can call it by saying func1(objA) (Automatically creates a copy)

Does anything similar exist in C#. By the way, I'm using Visual Studio 2005.

+6  A: 

As already explained, there's no equivalent to C++'s copy constructors.

Another technique is to use a design where the objects are immutable. For immutable objects there is no (semantic) difference between passing a reference and a copy. This is the way System.String is designed. Other systems (notably functional languages) apply this technique much more.

Bjarke Ebert
+12  A: 

No, there is no copy-constructor equivalent in C#. What you are passing (by value) is a reference.

ICloneable is also risky, since it is poorly defined whether that is deep vs shallow (plus it isn't very well supported). Another option is to use serialization, but again, that can quickly draw in much more data than you intended.

If the concern is that you don't want the method making changes, you could consider making the class immutable. Then nobody can do anything nasty to it.

Marc Gravell
A: 

can i pass reference type by value ? and can i pass value type by reference ? if yes Y ? if no Y ?

harry
A: 

This link shd answer ur question - http://msdn.microsoft.com/en-us/library/s6938f28(VS.80).aspx

isthatacode