confusion regarding hashtable.

A

archana

Hi all,

I am having one confusion regarding hashtable.

I am having function in which i am passing hashtable as reference. In
function i am creating one hashtable which is local to that function.
Then i am setting this hash table to hashtable which i am passing as
ref.

So my question is how scope is mention when i am assigning local
variable of function to reference parameter.

please correct me if i am wrong.

thanks in advance.
 
T

Terry Rogers

Hi all,

I am having one confusion regarding hashtable.

I am having function in which i am passing hashtable as reference. In
function i am creating one hashtable which is local to that function.
Then i am setting this hash table to hashtable which i am passing as
ref.

So my question is how scope is mention when i am assigning local
variable of function to reference parameter.

please correct me if i am wrong.

thanks in advance.

The ref keyword affects this:


Without the ref keyword the parameter variable is local to the method:

public void Method1()
{
Hashtable table = new Hashtable();
table.Add(1, "One");
Method2(table);

// table is still the hashtable created here
// so outputs false
Console.WriteLine(table.Contains(2));
}
public void Method2(Hashtable table1)
{
Hashtable table2 = new Hashtable();
table2.Add(2, "Two");

// this only reassigns the local "table1" reference
table1 = table2;
}

With the ref keyword you can change the reference:
public void Method1()
{
Hashtable table = new Hashtable();
table.Add(1, "One");
Method2(ref table);

// now table reference has been reassinged
// so this outputs false
Console.WriteLine(table.Contains(2));
}
public void Method2(ref Hashtable table1)
{
Hashtable table2 = new Hashtable();
table2.Add(2, "Two");

// this reassigns the reference which was passed in
table1 = table2;
}


Terry
 
J

Jon Skeet [C# MVP]

I am having one confusion regarding hashtable.

I am having function in which i am passing hashtable as reference. In
function i am creating one hashtable which is local to that function.
Then i am setting this hash table to hashtable which i am passing as
ref.

So my question is how scope is mention when i am assigning local
variable of function to reference parameter.

You need to be very clear about the difference between a parameter
passed *by* reference (i.e. where you've got "ref" in the signature)
and reference types where the reference is passed by value.

See http://pobox.com/~skeet/csharp/parameters.html for more info on
this.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top