Why can't I specify the ref parameter?

I have a method with a parameter of type ref ref, which I want to call by passing a parameter like the button ref.

Well, the compiler does not accept this, I need to change the control type ref to the type of the ref button.

Why?

+3
source share
5 answers

You can get around some input restrictions 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 link of any type to it, which is inferred from the 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);
        }
    }
+7
source

Because it will cause a lot of 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 ...
}
+25
source

#:

, ref, - (§12.3.3) ,

+7

ref , .

Show the code so we can discuss the details and alternatives.

+2
source

According to the C # specification:

If the formal parameter is a reference parameter, the corresponding argument in the method call must consist of the ref keyword, followed by a reference variable (§5.3.3) of the same type as the formal parameter.

Otherwise, it is possible that a value of an inappropriate type (to your button bound to the check box instance) will be assigned to the variable that you are passing.

+1
source

Source: https://habr.com/ru/post/1717751/


All Articles