Why DataSet is being passed by reference without explicitly passing out or ref parameter? [duplicate]
回答1
Strings are immutable, plus you are not modifying the string parameter (not that you can), but instead you are assigning a new reference to your parameter. The original remains in place.
With DataSet
, you are modifying its contents and since it is a mutable reference type, you see the change in the caller.
Try the following in Main
DataSet ds = new DataSet();
ds.Tables.Add(new DataTable("tbl3"));
FillDS(ds);
and then in FillDS
assign a new reference to your DataSet
like:
private static void FillDS(DataSet ds)
{
ds = new DataSet(); //Here
ds.Tables.Add(new DataTable("tbl1"));
ds.Tables.Add(new DataTable("tbl2"));
}
You will see that your DataSet
still holds the old values and nothing is modified after calling FillDS
回答2
Both string
and DataSet
are reference types. So in both cases you pass references.
In the AssignString
method, you don't change the string
instance you passed, but assign a new instance ("new name"
) to the variable name
. The fact that the name
variable actually was a parameter does not matter (though it's considered a bad practice to re-assign parameters).
In FillDS
you do not reassign a new instance, but access and manipulate the properties of the passed instance via ds.Tables....
.
Possible to use dataset as ref
A DataSet
is a Reference Type
by nature. Value Types
are primitive types like int
, bool
, double
, long
, etc.
DataSet
is not the better approch to transfer data. You could use generics
collections like List<T>
and create a class (a DTO
object for sample) which contains just the properties you need to bind into the form. With this you can get a better performance.
You could be sure if your query itno database to fill this dataSet is good query.
This article explain with some detail why is better using generics collections instead dataset. http://msdn.microsoft.com/en-us/magazine/cc163751.aspx