Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Why source DataSet value getting changed while passed and modified inside a function?

C#
DataSet output = new DataSet();
            SqlConnection con = new SqlConnection("Data                 Source=SERVER;Initial Catalog=Database;Integrated Security=True;");
            SqlCommand cmd = new SqlCommand("select 'value1'",con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(output);
            Test(output);
            MessageBox.Show(output.Tables[0].Rows[0][0].ToString());

        public void Test(DataSet dataSet)
        {
            MessageBox.Show(dataSet.Tables[0].Rows[0][0].ToString());
            //Modifying value here is getting effected to the source DataSet, Is it always passed by ref?

            dataSet.Tables[0].Rows[0][0] = "value2";

        }
Posted
Updated 15-Oct-11 6:33am
v2
Comments
Mehdi Gholam 15-Oct-11 11:36am    
Edit your question as it makes no sense.
OriginalGriff 15-Oct-11 11:37am    
Post the relevant code fragment for the method call, and the method itself.
Use the "Improve question" widget to edit your question and provide better information.
DaveAuld 15-Oct-11 12:34pm    
You should have used the 'improve question' to paste the code in the question to take advantage of the code formatters, and not used the comment, i have edited for you.
appyks 15-Oct-11 12:37pm    
Thank You DaveAuld

1 solution

The dataSet parameter is a reference to an object. The reference was passed by value and so changing it will not effect the original value. So the below code will only have effect inside the function and will not change the value of the output variable from the call Test(output).
C#
public void Test(DataSet dataSet)
{
    dataSet = new DataSet();
}

But when use the statement
C#
dataSet.Tables[0].Rows[0][0] = "value2";
inside the function you are changing the object being referenced by dataSet which changes the values in the object as expected.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900