Mohamed Ahmed Mohamed Ahmed - 3 months ago 9
C# Question

Why DataSet is being passed by reference without explicitly passing out or ref parameter?

I can't understand this code, here the same implementation for the DataSet object and string variable, but different output,.I can see the logic behind the output of the string variable, but for the DataSet, I can't understand why!

class Program
{

static void Main(string[] args)
{
DataSet ds = new DataSet();
FillDS(ds);
PrintDS(ds);
string name = "old";
AssignString(name);
PrintString(name);
}
private static void AssignString(string name)
{
name = "new name";
}
private static void PrintString(string name)
{
Console.WriteLine(name);
}
private static void FillDS(DataSet ds)
{
ds.Tables.Add(new DataTable("tbl1"));
ds.Tables.Add(new DataTable("tbl2"));
}
private static void PrintDS(DataSet ds)
{
foreach (DataTable item in ds.Tables)
{
Console.WriteLine(item.TableName);
}
}
}
//Output:
//tbl1
//tbl2
//old

Answer

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