Search code examples
c#dynamicreturn-type

C#, dynamic return type


What I need is a method that can return a type (no object, cause no casting allowed) following a condition. Here is an example:

??? right (string fullStr, int endPosition)
{
    string tmpStr = "";
    tmpStr = fullStr.Substring(endPosition);
    if(tmpStr.Length == 1)
        return tmpStr[0]; //return a char!!
    else
        return tmpStr; //return a string!!
}

I tried generics but I was only able to return the type that was coming in, (if a char came in a char was returned, and if a string came in a string was returned). I tried this:

public static T right<T>(T stringToCheck, int endPosition)
{
    if (typeof(T).ToString() == "System.String")
    {
        string fullString = (string)((object)stringToCheck);
        string response = "";
        response = fullString.Substring(endPosition);
        if (response.Length == 1)
        {
            return (T)((object)response[0]);
        }
        else
            return (T)((object)response);
        }
    return stringToCheck;
}

I can't use typecasting (returning an object), cant use ref params.

Calls to the method have to stay the same:

right(stringOrChar,int) -> returns string or char.

Thank You


Solution

  • The return type of a function must be typed. As with any other variable or operation, any type that inherits from the specified type is a valid return value (which is why object allows anything as a value).

    The logistics of the caller wouldn't make much sense; how would you know whether to type your variable as a char or a string in your example?

    Is there a particular reason that you can't return a string in all cases?