Bachalo
Bachalo

Reputation: 7219

Check if argument of type object casts to integer or string

I have a method that I want to serve as dual purpose, depending on whether the argument being passed is actually an integer or string value.

How would i check if 'info' in the following is an integer or string value?

public void Place (object info){


}

I know about overloading, but for reasons I won't go into can't change the calling method. Type 'object' is always being passed. Kind of kludgy but going to test for integer and string cast values.

Upvotes: 0

Views: 721

Answers (3)

Sievajet
Sievajet

Reputation: 3513

C# 7.0 introduced pattern matching. This enables matches based on a specific class or structure. Since you can't change the signature of the method, this is the best option at the moment.

Code becomes simpler using the is expression to assign a variable if the test succeeds:

public void Place( object info )
{
    if ( info is string infoString )
    {
        // use infoString here
    }
    else if ( info is int infoInt )
    {
        // use infoInt here                
    }
}

If statements are limited to test the input to match a specific single type. If you want to test specific cases, the switch pattern matching becomes a better choice:

public void Place( object info )
{
    switch ( info )
    {
        // handle a specific case
        case string infoString when infoString.Contains( "someInfo" ):
            // do something
            break;

        case string infoString:
            // do something
            break;

        case int infoInt when infoInt > 10:
            // do something
            break;

        case int infoInt:
            // do something
            break;

        default: 
        // handle any other case
        break; 
    }
}

Upvotes: 4

Ousmane D.
Ousmane D.

Reputation: 56433

Don't use object as the parameter, a better option would be to overload the method.

public void Place (string info){ ... }

public void Place (int info){ ... }

if you can't change the method signature for some reason then you'll need to do:

public void Place(object info)
{
       if(info is int){
           int result = (int)info;
           ...                   
       }
       else if (info is string){
           string result = (string)info;
           ...
       }
}

Upvotes: 4

Rahul
Rahul

Reputation: 77876

Or, make it a generic method like

public void Place<T> (T info)
{   
   // your code here
}

You can call it closing the type like

Place<int>(23) Or just Place(23)

Upvotes: 1

Related Questions