简体   繁体   中英

Dynamic return type of function in c#

I have a function which is like below:

private static *bool* Function()
{

if(ok)
return UserId; //string
else
return false; //bool

}

are there any way to do this? In stackoverflow there are some questions like this but I couldnt understand.

Seems like the TryXXX pattern is suitable in this case:

private static bool TryFunction(out string id)
{
    id = null;
    if (ok)
    {
        id = UserId;
        return true;
    }

    return false;
}

and then use like this:

string id;
if (TryFunction(out id))
{
    // use the id here
}
else
{
    // the function didn't return any id
}

Alternatively you could have a model:

public class MyModel
{
    public bool Success { get; set; }
    public string Id { get; set; }
}

that your function could return:

private static MyModel Function()
{
    if (ok)
    {
        return new MyModel
        {
            Success = true,
            Id = UserId,
        };
    }

    return new MyModel
    {
        Success = false,
    };
}

No, you can't do that.

Alternatives:

static object Function() {
    if(ok)
         return UserId; //string
    else
         return false; //bool
}

Or:

static object Function(out string userId) {
    userId = null;
    if (ok) {
         userId = UserId;
         return true;
    }
    return false;
}

Why would you want to do this in this scenario?

Just return null from the function. Check if the function returns null from where you are calling it.

If your scenario is other than what you have described in your question, then you may want to look at generics.

No. Instead, use an out parameter:

private bool TryGetUserId(out int userId) {
    if (ok) {
        userId = value;
        return true;
    }

    return false;
}

Call it like this:

int userId = 0;

if (TryGetUserId(out userId)) {
    // it worked.. userId contains the value
}
else {
    // it didnt 
}
private static string Function()
{

if(ok)
return UserId; //string
else
return ""; //string

}

Caller just need to check whether the return string is empty or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM