Parameter as reference but I am not using "ref"

  • Thread starter Thread starter Everton Berz
  • Start date Start date
E

Everton Berz

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
}

}
 
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.
 
Everton said:
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
 
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.
 
Back
Top