Dataset pass by ref

T

tshad

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?

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).

Thanks,

Tom
 
C

Cor Ligthert[MVP]

Tshad,

You do it 'by ref' if you instance a new dataset in the method, while the
dataset is not the return type of the method

Otherwise (by val) the reference will keep at the old reference as passed
and the new dataset will be disposed by the GC as the method goes out of
scope.
By ref the old one goes out of scope and will be disposed by the GC.

Cor
 
A

Alberto Poblacion

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".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top