Parameter as reference but I am not using "ref"

Parameter as reference but I am not using "ref"

Post by Everton Be » Sun, 14 Oct 2007 01:22:42


Hi,

In the follow program I would like to have the parameter "c" in method
"doSomething" as a value parameter, but it's running as a reference
parameter. Why? How can I get parameter "c" as a value (or clone,
copy)?

Current result:
value1
value2

Expected result:
value1

class Program
{
static void Main(string[] args)
{
SqlCommand sqlCommandSelect = new SqlCommand();
sqlCommandSelect.Parameters.AddWithValue("@col1",
"value1");
doSomething(sqlCommandSelect.Parameters);

foreach (SqlParameter param in
sqlCommandSelect.Parameters)
{
Console.WriteLine(param.Value);
}
Console.ReadLine();
}

private static void doSomething(SqlParameterCollection c)
{
c.AddWithValue("@col2", "value2");
//I want to use the new value only here
}

}
 
 
 

Parameter as reference but I am not using "ref"

Post by Nicholas P » Sun, 14 Oct 2007 01:33:34

Everton,

SqlParameterCollection is a reference type. The parameter itself can
not be changed, but the parameter is a reference. You can still modify what
the refrerence points to.


--
- Nicholas Paldino [.NET/C# MVP]
- XXXX@XXXXX.COM

 
 
 

Parameter as reference but I am not using "ref"

Post by .NET/ C# » Sun, 14 Oct 2007 01:42:57

Hi,


--
Ignacio Machin
www.laceupsolutions.com
Mobile & warehouse Solutions.



Take a look at http://www.yqcomputer.com/ 's a
very good explanation about parameters in C#
 
 
 

Parameter as reference but I am not using "ref"

Post by Peter Duni » Sun, 14 Oct 2007 02:15:47


As Nicholas says, you can't. You'd have to clone it explicitly before
passing it, as the type is a reference type and so a reference is always
passed. It's passed by value, but it's still a reference.

This (or at least, the more general topic) is a common question and Jon
Skeet's web site includes an article that should help:
http://www.yqcomputer.com/ ~skeet/csharp/parameters.html

Pete
 
 
 

Parameter as reference but I am not using "ref"

Post by Everton Be » Tue, 16 Oct 2007 16:25:59

Thank you for answer.

I really did not know that SqlParameterCollection is a reference
type.
There is no Clone method in this class, I think I need to clone my
SqlCommand object.