How to Check If an Object Is Nullable

How to check if an object is nullable?

There are two types of nullable - Nullable<T> and reference-type.

Jon has corrected me that it is hard to get type if boxed, but you can with generics:
- so how about below. This is actually testing type T, but using the obj parameter purely for generic type inference (to make it easy to call) - it would work almost identically without the obj param, though.

static bool IsNullable<T>(T obj)
{
if (obj == null) return true; // obvious
Type type = typeof(T);
if (!type.IsValueType) return true; // ref-type
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
return false; // value-type
}

But this won't work so well if you have already boxed the value to an object variable.

Microsoft documentation: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type

C# How to check if an object is nullable

The call Nullable.GetUnderlyingType() doesn't return anything meaningful for typeof(string). The documentation mentions:

Returns the underlying type argument of the specified nullable type.

Return Value

The type argument of the nullableType parameter, if the nullableType parameter is a closed generic nullable type; otherwise, null.

In other words, it only returns something useful if you actually pass it a type that implements Nullable<T>, for example int?, bool?, and so on. That is what's being meant by a "nullable type" here.

You can also see its intended usage in the code from Marc's answer to the question you link to:

static bool IsNullable<T>(T obj)
{
// ...
if (!type.IsValueType) return true; // ref-type
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
}

How to check if object is null or not except == null

The easiest way to check is entity == null. There is no shorter way to do that.

Note that there is a method for this in the standard lib:

Objects.isNull(Object obj)

And another one which is the opposite of the above one:

Objects.nonNull(Object obj)

And there is yet another one which can be used to force a value to be not null, it throws a NullPointerException otherwise:

T Objects.requireNonNull(T obj);

Note: The Objects class was added in Java 7, but the isNull() and nonNull() methods were added only in Java 8.

Correct way to check if a type is Nullable

Absolutely - use Nullable.GetUnderlyingType:

if (Nullable.GetUnderlyingType(propertyType) != null)
{
// It's nullable
}

Note that this uses the non-generic static class System.Nullable rather than the generic struct Nullable<T>.

Also note that that will check whether it represents a specific (closed) nullable value type... it won't work if you use it on a generic type, e.g.

public class Foo<T> where T : struct
{
public Nullable<T> Bar { get; set; }
}

Type propertyType = typeof(Foo<>).GetProperty("Bar").PropertyType;
// propertyType is an *open* type...

How to check if one value of an object is null

You can gather all your strings into an array and then run .Any() method:

if (new[] { obj.string1, obj.string2, obj.string3 }.Any(string.IsNullOrWhiteSpace))
{

}

Alternatively you can use reflection (which will affect your code's performance), to scan all the strings of your object and check your condition:

var anyEmpty = obj.GetType().GetProperties()
.Any(x => x.PropertyType == typeof(string)
&& string.IsNullOrWhiteSpace(x.GetValue(obj) as string));

Java: How to check if object is null?

Edited Java 8 Solution:

final Drawable drawable = 
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());

You can declare drawable final in this case.

As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.

What is the best practice to check if an object is null in C++

I want to check if the object is null.

Congratulations, your Object object is not null. null is not a possible value for object to be.

A close analog might be to test that it is different to a default-constructed Object, if Object is default-constructable.

EXPECT_TRUE(my_object != Object{})

C# Checking if Object is Null

  1. It is possible that the try block will never assign a value to ro and thus it will be unassigned outside of try block. To fix that, assign a value:

    RootObject ro = null;
  2. Since ro could be null, you need to check for that in your if statement before you try to access a member:

    if (ro != null && ro.Region != null)
    {
    Row.Region = ro.Region;
    Row.SubRegion = ro.Subregion;
    }

Detecting a Nullable Type via reflection

Well firstly, Nullable<T> is a struct, so there isn't an object as such. You can't call GetType(), as that will box the value (at which point you either get null and thus an exception, or a boxed non-nullable value and therefore not the type you want).

(Boxing is what's messing up your assertion here - I would assume that IsType accepts object.)

You can use type inference though to get the type of the variable as a type parameter:

public bool IsNullable<T>(T value)
{
return Nullable.GetUnderlyingType(typeof(T)) != null;
}

That's not a huge amount of use when you know the exact type at compile-time as in your example, but it's useful for generics. (There are alternative ways of implementing it, of course.)

What's your real life situation? I assume it's not an assertion like this, given that you know the answer to this one at compile time.



Related Topics



Leave a reply



Submit