Manpreet Singh Dhillon
Manpreet Singh Dhillon

Reputation: 903

Why does SqlConnection use reference type when passed as parameter?

I am writing following function that gets one SqlConnection parameter.

    private void doSomething(SqlConnection cnn)
    {
        //do something
        cnn.Close();
    }

I am calling this method as shown below:

    private void RnD_Load(object sender, EventArgs e)
    {
        //line 1
        SqlConnection cnn = new SqlConnection();
        //line 2
        cnn.ConnectionString = "my connection string";
        //line 3
        cnn.Open();
        //line 4
        doSomething(cnn);
        /* here cnn should be in open state, but it closes as soon as doSomething is done */
        //line 5
        if (cnn.State == ConnectionState.Open)
        {
            Console.Write("open");
        }
        else
        {
            Console.Write("closed");
        }
    }

doSomething function closes connection after it finishes its work. But it is going above my head that why cnn's state is closed at line 5 after call to doSomething function at line 4? We all know that parameters in C# are passed by value by default. When cnn is being passed by value then why is it getting closed at line 5?

Upvotes: 1

Views: 669

Answers (3)

Denis Kurkov
Denis Kurkov

Reputation: 11

Passing reference type object is done by coping a pointer to that object. So you do not copy chunk of memory, you just copy pointer to same memory. It's like coping a shortcut to file instead of coping a file.

Upvotes: 0

itsme86
itsme86

Reputation: 19526

I think you're confused about what calling by value vs reference means.

When passed by value, the doSomething() method is still free to change the state of the object, and those changes will be reflected in RnD_Load() when it uses that object. What doSomething() can't do is say that cnn in RnD_Load() now points to a different object (or null).

If, however, you had passed cnn by reference (by adding the ref qualifier to the parameter), then doSomethign() could say cnn = someNewSqlConnectionObject; and cnn in RnD_Load() would now point to that new object.

Upvotes: 0

nAviD
nAviD

Reputation: 3281

There are reference types and value types in C# sharp. All primitive types like int, string, Datetime,... are value types which means unless you use ByRef keyword they will be passed as value to a function. But unlike these types every other Objects that are instantiated from classes are reference types which always will be pass as a ByRef parameter. you may wonder why following code equals to false even though the values are the same! :

(new Person("John"))==(new Person("John")) // equals to false

Upvotes: 1

Related Questions