Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a method performs operations on a reference type is there any need to return it?

Tags:

c#

If I have a method that operates exclusively on a reference type variable (e.g. a datatable) and modifies it, is there any need to return that variable from the method??

For example, the following method goes through a datatable and trims all the values within it and then returns the datatable to the caller:

        private DataTable TrimAllDataInDataTable(DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    row[dc] = row[dc].ToString().Trim();
                }
            }

            return dt;
        }

Would it be better if this method returns void? Seems pretty pointless to return it (?), but do you think that it reads better if it returns the object after operating on it (like it does at the moment)??

like image 274
Calanus Avatar asked Dec 19 '25 03:12

Calanus


1 Answers

To me, when a method returns a reference type, I expect it to be a new object. I'd pick making it return void.

A question: is there any reason for this method to not be a member of the DataTable class? I think that DataTable.TrimAllData() would work even better

like image 122
Steef Avatar answered Dec 20 '25 16:12

Steef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!