Home > Enterprise >  In c#, how to convert T? to T
In c#, how to convert T? to T

Time:09-30

Similar code works fine in kotlin but not work in c#

public static class Helper
{
    public static T RequireNotNll<T>(T? obj,string? message) {
        if (obj == null) {
            throw new Exception(message ?? "obj must not null");
        }
        return obj;
    }
}

please help

CodePudding user response:

? has different meanings for value types and for reference types. The latter applies only in a nullable context, (#nullable enable). So you need two methods.

For value types, use the code provided by Joel Coehoorn:

public static T RequireNotNull<T>(T? obj,string? message) where T : struct {
    if (!obj.HasValue) {
        throw new Exception(message ?? "obj must not be null");
    }
    return obj.Value;
}

For reference types, use the null-forgiving operator ! to convince the compiler:

public static T RequireNotNull<T>(T? obj,string? message) where T : class {
    if (obj is null) {
        throw new Exception(message ?? "obj must not be null");
    }
    return obj!;
}

CodePudding user response:

You were close:

public static T RequireNotNll<T>(T? obj,string? message) {
    if (obj == null) {
        throw new Exception(message ?? "obj must not null");
    }
    return obj.Value;
}
  • Related