1

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

Javier
  • 103
  • 1
  • 6

3 Answers3

4

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 .
  • 8,110
  • 5
  • 38
  • 48
1

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

Community
  • 1
  • 1
RichardOD
  • 28,883
  • 9
  • 61
  • 81
0

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
  • 15,459
  • 7
  • 44
  • 62
  • 1
    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 Jul 05 '09 at 14:13