Silny ToJa
Silny ToJa

Reputation: 2261

How cast value as tuple (string, bool)

It is possible to cast as tuple in this way?

(string value, bool flag) value1 = MethodInfo.Invoke(this, param) as (string, bool);

Unfortunately it throw:

"The as operator must be used with a reference type or nullable type ('(string, bool)' is a non-nullable value type)"

Only work in this way:

Tuple<string, bool> value1 = MethodInfo.Invoke(this, param) as Tuple<string, bool>;

Upvotes: 2

Views: 822

Answers (1)

Sweeper
Sweeper

Reputation: 271485

You can use a cast expression to cast:

(string value, bool flag) tuple = ((string, bool)) MethodInfo.Invoke(this, param);

But unlike using as, this will crash if the return value of Invoke is not a (string, bool). If you don't like that, you can use pattern matching:

if (methodInfo.Invoke(this, param) is (string value, bool flag))
{
    Console.WriteLine($"({value}, {flag})");
    // assign it to a new variable if you want it as one "thing":
    (string value, bool flag) tuple = (value, flag);
}

Upvotes: 3

Related Questions