Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of Nullable objects with different underlying type?

Tags:

c#

I have a number of nullable objects of different types (e.g. DateTime?, Guid?) that I want to check for a value.

I'd like to avoid code like this:

return SomeGuid.HasValue || SomeBool.HasValue || SomeDateTime.HasValue

but it does not seem possible to create an array of Nullable<object>. I was hoping to do something like:

return new Nullable<object>[] { SomeGuid, SomeBool, SomeDateTime }.Any(o => o.HasValue);
like image 330
Ben Foster Avatar asked May 25 '26 11:05

Ben Foster


1 Answers

object is nullable per definition.

So the following works:

Guid? guid = null;
bool? boolean = null;
DateTime? date = DateTime.Now;

var test = new object[] { guid, boolean, date }.Any(o => o != null);

Do note Nullable<T> requires T to be a struct, i.e. a value type (not a reference type). object is a reference type.

like image 117
ken2k Avatar answered May 28 '26 00:05

ken2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!