shaker
shaker

Reputation: 1

What does the keyword ref mean in C#?

Below is my code please explain what is ref cboListType.

Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}

Upvotes: 0

Views: 1289

Answers (7)

SquidScareMe
SquidScareMe

Reputation: 3218

From MSDN

The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.

Upvotes: 0

CharithJ
CharithJ

Reputation: 47530

Refer to the same DropDownList that was passed into the method.

Here for more details.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292425

The ref keyword indicates that a parameter is passed by reference.

In the code you posted, it's perfectly useless, because the method doesn't change the value of the parameter (changing properties of the parameter doesn't require passing it by reference, at least not if it is a reference type)

Upvotes: 3

m0skit0
m0skit0

Reputation: 25873

ref means parameter is passed by reference, not by value. More detailed info

Upvotes: 0

Polyfun
Polyfun

Reputation: 9639

I assume this is a System.Web.UI.WebControls.DropDownList, and it almost certainly should not be declared ref.

Upvotes: 1

Josh
Josh

Reputation: 2975

The C# ref keyword causes a method to refer to the same variable that was passed into the method. Any changes made to that variable are reflected in that variable when control is passed back.

Upvotes: 1

Andrey Agibalov
Andrey Agibalov

Reputation: 7694

ref keyword means "pass by reference". When you pass some DropDownList reference to LoadListTypes() this reference may be changed. So after this call, the reference you've passed could refer to absolutely another object.

void func(ref MyClass mc)
{
  mc = new MyClass(2);
}

MyClass mc = new MyClass(1);
MyClass mc2 = mc;
// mc and mc2 are the same
func(ref mc);
// mc and mc2 may differ

Upvotes: 2

Related Questions