Javier
Javier

Reputation: 103

calling a method over variable of type object in vb and c#

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

Answers (3)

RichardOD
RichardOD

Reputation: 29157

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

Upvotes: 1

Timothy Carter
Timothy Carter

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

g .
g .

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

Related Questions