tags:

views:

113

answers:

3

in vb I can do that

sub SetFocusControl(byref ctl as object)
  ctl.Focus
end sub

in c# the compiler complaint that object doesn't have a Focus method

void SetFocusControl(ref object ctl)
{
  ctl.Focus();
}

how can I do the same in c#?

thanks

+4  A: 

Instead of using object, use the type that has the Focus method.

void SetFocusControl(Control ctl)
{
    ctl.Focus();
}

And I don't think you need the ref.

I'd also ask whether you need a separate method. Could you not just call the Focus method directly?

ctl.Focus();

If you don't know the type or if it has a Focus method you could do this.

void SetFocusControl(object ctl)
{
    Control control = ctl as Control

    if (null == control)
        return;

    control.Focus();
}
g .
Thanks, Your code works fine, and you are right I don't need to use ref.
Javier
A: 

I can't speak to why this works in VB, but in c#, you've declared ctl as type object. Object has four public methods ToString, GetHashcode, GetType and Equals. To do this in c# you would need the method to accept a different type, like Control, that has a Focus method (or an interface that has that method), or after you receive the argument you will need to do type conversion and checking to get the object into a type that has a Focus method.

Timothy Carter
VB allows late binding easily- you can change this behaviour by using Option Strict. See here- http://msdn.microsoft.com/en-us/library/zcd4xwzs(VS.80).aspx
RichardOD
+1  A: 

Javier- you should read about why C# is statically typed.

RichardOD