Math
Math

Reputation: 389

C# implicit conversion without cast

I am converting VB.net code to C# and I am facing a problem. With VB.net, I have functions that use OBJECT parameters. These parameters are usually of 2 differents types which have the same methods that I need. Example:

Public Sub test(param1 as Object)
    param1.show()
End Sub

With C#, I do the same kind of function, but the compiler won't accept it.

public void test(object param1)
{
    param1.show(); // Error on .show (not found)
}

I should probably cast the parameter in some way, but I need to send different types to the function. Is it possible?

Upvotes: 1

Views: 301

Answers (3)

Slai
Slai

Reputation: 22866

Or you can make separate function for each type:

public void test( type1  param1) { param1.show(); }
public void test( type2  param1) { param1.show(); }
public void test(dynamic param1) { param1.show(); } // for the rest of the types

Upvotes: 0

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

If you have Option Strict Off set using Object is the equivalent to using dynamic in C#

public void test(dynamic param1)
{
    param1.show();
}

However, I really, REALLY, recommend you do not do that. dynamic was invented to help with writing late bound code (that is also the job Object served in VB6 when this feature was introduced), you really should use a class with a interface to get the strong type info for your code.

Upvotes: 3

Igor
Igor

Reputation: 62213

This is why interfaces exist.

public interface IShowable {
    void show();
}

class YourClassFromAbove {
    public void test(IShowable param1)
    {
        param1.show();
    }
}

Any type passed in must implement the IShowable contract which solves the problem.

Upvotes: 8

Related Questions