Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I cast a ref parameter?

Tags:

c#

I have a method with a ref control type parameter which I want to call by passing a ref button type parameter.

Well the compiler doesn't accept this, I have to change the ref control type to ref button type.

Why ?

like image 432
programmernovice Avatar asked Sep 15 '09 18:09

programmernovice


3 Answers

Because this will cause many problems ...

public void DoDarkMagic(ref Control control)
{
    control = new TextBox();
}

public void Main()
{
    Button button = new Button();

    DoDarkMagic(ref button);

    // Now your button magically became a text box ...
}
like image 185
Daniel Brückner Avatar answered Nov 15 '22 08:11

Daniel Brückner


You can get around some of the typing limitations with generics.

void Test<T>(ref T control)
   where T: Control
{
}

Now you can call:

Button b = new Button() 
Test(b);

You can pass a reference of any type into it that derives from control.

Real life scenario:

 protected static void BindCollection<T>(
        T list
        , ref T localVar
        , ref ListChangedEventHandler eh // the event handler
        , ListChangedEventHandler d) //the method to bind the event handler if null
        where T : class, IBindingList
    {
        if (eh == null)
            eh = new ListChangedEventHandler(d);

        if (list != null && list != localVar)
        {
            if (localVar != null)
                localVar.ListChanged -= eh;

            localVar = list;

            list.ListChanged += eh;
        }
        else if (localVar != null && list == null)
        {
            localVar.ListChanged -= eh;
            localVar = list;
        }
    }

public override BindingList<ofWhatever> Children
    {
        get{//..}
        set
        {
           //woot! a one line complex setter 
           BindCollection(value, ref this._Children, ref this.ehchildrenChanged, this.childrenChanged);
        }
    }
like image 32
Brian Rudolph Avatar answered Nov 15 '22 08:11

Brian Rudolph


From the C# specification:

When a formal parameter is a reference parameter, the corresponding argument in a method invocation must consist of the keyword ref followed by a variable-reference (§12.3.3) of the same type as the formal parameter

like image 31
Pete OHanlon Avatar answered Nov 15 '22 07:11

Pete OHanlon