tshad said:
I thought a DataSet is passed always by reference.
If that is the case, why do you need the "ref" keyword before it if you
want to change it in another routine?
The DataSet is a reference-type. When passing it by value, you are
passing "the value of the reference". When using "ref", you are passing "a
reference to the reference".
When you pass the DataSet without the "ref" keyword, the other routine
can change the *contents* of the dataset by means of the referece. However,
when you use "ref", the routine can also change the allocation of DataSet
itself (for instance, it can do a "new" and return a reference to the new
DataSet).
For example:
I define it in A and A calls B and B changes it and it returns to A (where
the changes are gone if you don't have the ref keyword).
Example 1: Pass by value.
void DoSomething(DataSet ds)
{
ds.Tables.Add(new DataTable()); //Modify contents of DataSet
}
//Call:
DataSet ds = new DataSet();
DoSomething(ds); //ds will get a table added
void DoSomethingElse(DataSet ds)
{
ds=new DataSet(); //Useless. the new ds does not get returned.
}
//Call:
DataSet ds;
DoSomethingElse(ds); //Does not bring us back an allocated ds.
//here ds is still null.
Example 2: Pass by reference
void DoSomethingElse(ref DataSet ds)
{
ds=new DataSet();
}
//Call:
DataSet ds;
DoSomethingElse(ref ds);
//Here ds is not null.
//Note that in this specific example it would be better to use "out" instead
of "ref".