Search code examples
c#methodssvc

set multiple return value for method declaration


I have a function as below:

  public var UpdateMapFetcher(int stationID, int typeID)

I need this function to return either string or int.

My return value is set as below

 if (finaloutput == "System.String")
        {
            // param1[i] = Convert.ChangeType(typeID_New.ToString(), typeof(string));
            returnvalue = returnvalue.ToString();
            return returnvalue;
        }
        else if (finaloutput == "System.Int32")
        {
            int a=0;
            a = Convert.ToInt32(returnvalue);
            return a;
        }

How to have either one data type as return value in dynamic environment.


Solution

  • My intuition tells me, that you are trying to convert string value to some type. In that case you can use:

    public T UpdateMapFetcher<T>(int stationID)
    {
        //var someValue = "23";
        return (T)Convert.ChangeType(someValue, typeof(T));
    }
    //then
    var typed = UpdateMapFetcher<int>(6);
    

    In case you don't know T, you can use mapping (0-int, 1-string, etc.):

    public object UpdateMapFetcher(int stationID, int type)
    {
        var typeMap = new []{ typeof(int), typeof(string)};
        //var someValue = "23";
        return Convert.ChangeType(someValue, typeMap[type]);
    }
    //then
    var untyped = UpdateMapFetcher(6, 0/*0 is int*/);
    if (untyped.GetType() == typeof(int))
    { /*is int*/
    }
    

    Another solution is to use implicit conversions:

    public class StringOrInt
    {
        private object value;
        public ValueType Type { get; set; }
    
        public static implicit operator StringOrInt(string value)
        {
            return new StringOrInt()
            {
                value = value,
                Type = ValueType.String
            };
        }
        public static implicit operator StringOrInt(int value)
        {
            return new StringOrInt()
            {
                value = value,
                Type = ValueType.Int
            };
        }
        public static implicit operator int(StringOrInt obj)
        {
            return (int)obj.value;
        }
        public static implicit operator string(StringOrInt obj)
        {
            return (string)obj.value;
        } 
    }
    public enum ValueType
    {
        String,
        Int
    }
    

    And then (simplified):

    public static StringOrInt UpdateMapFetcher(int stationID, int typeID)
    {
        if (typeID == 0)
            return "Text";
        return 23;
    }
    
    private static void Main(string[] args)
    {
        var result = UpdateMapFetcher(1, 1);
        if (result.Type == ValueType.String) { }//can check before
        int integer = result;//compiles, valid
        string text = result;//compiles, fail at runtime, invalid cast      
    }