George2
George2

Reputation: 45771

C# passing ref type parameter issue

Suppose I have the following code snippets, i.e. goo call foo, DataTable created by goo and foo will only call Rows.Add. Then goo will use the updated data of the DataTable instance from foo.

My question is, in my scenario, any differences or benefits compared of using with and using without ref parameter?

I am using C# + .Net 3.5 + VSTS2008.

    void foo (ref DataTable dt)
    {
        // call Row.Add on dt
    }

    void goo()
    {
        DataTable dt1 = ...; // create a new instance of DataTable here
        foo (ref dt1);
        // read updated content of DataTable by foo here
    }

Upvotes: 0

Views: 7287

Answers (5)

Jon Skeet
Jon Skeet

Reputation: 1500485

Others have answered already, but if you want more information you might want to read my article on parameter passing in C#.

(Everyone is right - if you just want to change the data in the object, you're fine passing the argument by value. If you want to change which object the caller's variable refers to, then you pass by reference.)

Upvotes: 0

jlembke
jlembke

Reputation: 13517

You don't need the ref parameter unless you intend on getting a different object back. The DataTable is a reference object so what you are really passing is a pointer to a pointer. If all you intend is for the called function to make changes to your instance you don't need ref.

Upvotes: 3

Mark Brackett
Mark Brackett

Reputation: 85655

You only use ref if you intend to change what dt points to. Eg., if you wanted to replace it with a different DataTable (or, a type deriving from DataTable).

In this case, you are just using dt, so there's no reason to use ref. Since DataTable is a class, any changes made to it will be visible outside of foo.

Upvotes: 4

Erich
Erich

Reputation: 655

In that case, there is absolutely zero difference between using a ref or a non-ref parameter. The only thing a ref param will allow you to do in this situation is "dt=new DataTable()" and have it affect the main function.

It is better to only use a ref param when you need it, otherwise it creates messier code.

Upvotes: 2

Kevin LaBranche
Kevin LaBranche

Reputation: 21078

The only difference / benefit I see is that the code would be more clear if you didn't pass it by reference.

Upvotes: 0

Related Questions