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 ?
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 ...
}
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);
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With