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
}
}
Nicholas Paldino [.NET/C# MVP] - 12 Oct 2007 17:33 GMT
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.

Signature
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
> Hi,
>
[quoted text clipped - 34 lines]
>
> }
Ignacio Machin ( .NET/ C# MVP ) - 12 Oct 2007 17:42 GMT
Hi,

Signature
Ignacio Machin
www.laceupsolutions.com
Mobile & warehouse Solutions.
> 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)?
Take a look at http://www.yoda.arachsys.com/csharp/parameters.html it's a
very good explanation about parameters in C#
Peter Duniho - 12 Oct 2007 18:15 GMT
> 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)?
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.pobox.com/~skeet/csharp/parameters.html
Pete
Everton Berz - 15 Oct 2007 08:25 GMT
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.
--
Everton
> > 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
[quoted text clipped - 9 lines]
>
> Pete