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

3 Answers 3

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Your code works fine, and you are right I don't need to use ref.
1

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

Comments

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.

1 Comment

VB allows late binding easily- you can change this behaviour by using Option Strict. See here- msdn.microsoft.com/en-us/library/zcd4xwzs(VS.80).aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.