How to preserve null in system.array - C#?

I got the first row of an excel sheet with the following code.

Excel.Range firstRow = ws.UsedRange.Rows[1];
var row = (System.Array) firstRow.Cells.Value;
List<object> Array = row.OfType<object>().ToList();

row consists of null values.

Eg. enter image description here

The problem is when it is converted in to list, all the null values are lost. (After this statement)

 List<object> Array = row.OfType<object>().ToList();

Eg. enter image description here

Any ideas how to prevent this from happening ?

Upvotes: 1

Views: 207

Answers (1)

Chris
Chris

Reputation: 27609

From looking at what you are doing Cast would be more appropriate than OfType.

List<object> Array = myvalues.Cast<object>().ToList();

This should do what you want and basically just tell it that all objects should be cast to type object. This will preserve the null.

The reason for the difference is that OfType does a check for current is TResult before returning the cast object and of course null is object will return false and thus it gets dropped. The corollary of this is of course that Cast can throw exceptions if misused (eg Cast<int> on the above sample would throw an InvalidCastException whereas OfType<int> would just return the items that could be cast to ints.

From: CAST AND OFTYPE

There’s one important case to consider where Cast will successfully return a value and OfType will ignore it: null references (with a nullable return type). In normal code, you can cast a null reference to any nullable type (whether that’s a reference type or a nullable value type). However, if you use the "is" C# operator with a null value, it will always return false. Cast and OfType follow the same rules, basically.

Upvotes: 5

Related Questions