How to pass a SqlCommand "By Value"

In this snippet:
- How to pass a
SqlCommand "By Value"

You cannot pass a reference type "by value", but what you can do is pass in a copy of the original object. You can
do that for any type that supports "ICloneable" via the Clone() method.

By default when you pass a variable reference into a method, it depends on if that variable type is a reference type or a value type. Most types, like
SqlCommand, are a reference type. All the basic types like int, bool, long, are value types.

Value types are stored on the "stack". When they are passed into a method, that method gets it's own copy of that varible value. So that value is now on the stack twice. So any changes to the copy is not reflected in the calling method.

reference types are stored in the "heap". A pointer to that object instance is passed into a method. That method gets it's own pointer to that same object instance. Since that method has a pointer to the orginal object, any changes to that object are affecting the "original" object. There is NO way to get around this. What the calling method cannot do is reassign that instance to a new instance of that type. Well it can, but then it now points to that new instance, and any changes to it does not affect the original.

There are two operators you can apply to a method parameter "out" and "ref". When you apply either of these to a reference type the calling method can reassign the object to a new instance. Then the keyword causes that reassignment to affect the orginal calling methods pointer to the object to now also point at the new instance.

So, in short, you can prevent a called method from reassigning a variable to a new instance, but you cannot prevent it from modifying the instance that you pass in.

What you can do is pass your SqlCommand to ICloneable to do the clone.

For Example:

C#
SqlCommand myCommand = new SqlCommand(MySqlString)
ICloneable myCloneableComand = (ICloneable)myCommand;
SomeClass obj = new SomeClass();
obj.SomeMethod(myCloneableComand.Clone());



The
Parameters collection is a reference type. If multiple threads
access their own clone of the command, they will most likely be working
with the same parameters collection. So I would discourage passing
command clones to multiple threads.