Limit T to int?

How can I solve this error? msg?

static public class Blah
{
    public static T val<T>(this bool b, T v) { return b == true? v:0; }
}

Error

Type of conditional expression cannot be determined because there is no implicit conversion between 'T' and 'int
+3
source share
7 answers

In C # there is no way to do this. You can do

where T: struct and make T be a value type, but that is still not enough.

Or you can do

default(T)which is 0 when T is int.

+2
source

If you want T to be int, accept int rather than T. Otherwise, consider returning the default value (T) if b == false.

return b ? v : default(T);

If T is int, it will return 0. If it is a reference type, it will be zero. And further and further ..

+14
source

generics, int?

// No need to compare b to true...
public static int val(this bool b, int v) { return b ? v : 0; }

default(T), .

public static T val<T>(this bool b, T v) { return b ? v : default(T); }

default(T) 0 int , false bool s, null ...

+5

T:

public static T val<T>(this bool b, T v) { return b == true? v : default(T); }


+5

v : 0 v : default(T), . int, .

+2

T , :

public static int val(this bool b, int v)
{
    return b ? v : 0;
}

, , :

public static int val<T>(this bool b, T v) where T : struct
{
    return b ? v : default(T);
}
+2

Srsly!

" T int", , strong-typing:

static public class Blah
{
    public static int val(this bool b, int v) { return b == true? v:0; }
}

!:)

, ?
+2

Source: https://habr.com/ru/post/1742497/


All Articles