Karlen M
Karlen M

Reputation: 141

How to convert ObjectResult<int?> to IEnumerable<int?>

I do understand that code I wrote is wrong, so don't leave a comment that my code wrong. I know that.

Something like

ObjectResult<int?> obj = new ObjectResult<int?> as IEnumerable

I can't instantiate ObjcetResult, because it is protected class. And I can't change the access modifier.

Upvotes: 0

Views: 2754

Answers (1)

user47589
user47589

Reputation:

First, to answer your question:

You can't directly convert an ObjectResult<int?> to IEnumerable<int>. While IEnumerable<T> is covariant, there isn't an inheritance relationship between int? and int.

That said, you can cast it directly to an IEnumerable<int?>:

(IEnumerable<int?>)objResult

If you want an IEnumerable<int>, you can do:

var result = objResult.Where(x => x.HasValue).Select(x => x.Value);

Second, ObjectResult isn't a "protected" class, it's an abstract class. ObjectResult<T> is a sealed class. Neither abstract nor sealed are access modifiers.

Upvotes: 4

Related Questions