Reputation: 103
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
Upvotes: 1
Views: 324
Reputation: 15785
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.
Upvotes: 0
Reputation: 8270
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();
}
Upvotes: 4