Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

pass by reference?

How do I call GetClientDSN(ref string)  ?

How do I pass in my parameter by reference in C#?
Tom Knowlton
Tom Knowlton
2 Solutions
string is automatically passed by reference in c# and so are the objects.. but if you need to pass any explicitly by ref, just use the keyword ref in the parameter declaration..

private bool test(ref int a)


int b = 0;
bool check = this.test(ref b);
This is something worth spending some time on to get your understanding right. Basically there are two Types (http://msdn2.microsoft.com/en-US/library/3ewxz6et%28VS.80%29.aspx) of variables: value-types  and reference-types. You can pass variables as arguments by Value or by Reference. But Value and Reference Types should not be confused with passing by value or reference.

A string is in fact a reference type. Quoting from MSDN (why say it again if it has been said properly already):
"A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref (or out) keyword. For simplicity, the following examples use ref."

So, to pass a string to a method, and have any changes persist outside the method, you need to pass it by reference:
public void GetClientDSN(ref string myString)
    myString = "b";

And to call it...
public void TestCall()
    string testString = "a";
    GetClientDSN(ref testString); // <-------------NOTE the "ref" keyword here as well
    Console.WriteLine(testString); // writes "b"


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now