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

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

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-07-04 shell script operate the date
2019-07-04 Running .sh scripts in Git bash
2019-07-04 What is the !! (not not) operator in JavaScript?
2019-07-04 JavaScript-Load-Image
2019-07-04 jquery .each
2019-07-04 JavaScript json loop item in array
2019-07-04 Make jQuery throw error when it doesn't match an element
点击右上角即可分享
微信分享提示