dotnet/reactive · error · ArgumentNullException

Value cannot be null. (Parameter 'source')

Error message

Value cannot be null. (Parameter 'source')

What it means

Cast<TSource,TResult> is an extension on IAsyncObservable<TSource> and throws ArgumentNullException when the source is null. Like all AsyncRx operators it validates inputs up front rather than failing inside the subscription pipeline.

Solutions

  1. Ensure the source observable is non-null before calling Cast
  2. Replace a null source with AsyncObservable.Empty<TSource>() when 'no source' is a valid state
  3. Null-check the method returning the observable and handle the null branch explicitly

Example fix

// before
IAsyncObservable<object> src = maybeNull;
var ints = src.Cast<object, int>();
// after
if (src == null) src = AsyncObservable.Empty<object>(Scheduler.Default);
var ints = src.Cast<object, int>();
Defensive patterns

Strategy: validation

Validate before calling

if (source == null) throw new InvalidOperationException("Cannot Cast a null source observable");

Type guard

bool IsObservable<T>(IAsyncObservable<T> s) => s is not null;

Try / catch

try { var result = src.Cast<object, int>(); }
catch (ArgumentNullException ex) when (ex.ParamName == "source") { /* fall back to Empty source */ }

Prevention

When it happens

Trigger: Invoking source.Cast<TSource,TResult>() on a null IAsyncObservable<TSource>, or Cast(null) via static call syntax.

Common situations: Chaining off a factory method that returned null; LINQ-style pipelines where an earlier operator produced null; conditional source assignment left unset.

Related errors


AI-assisted analysis of dotnet/reactive@94b5d5ab91 (2026-09-15). Data as JSON: /api/errors/70cc1c0091996f95. Report an issue: GitHub.

Appendix: source

Thrown at AsyncRx.NET/System.Reactive.Async/Linq/Operators/Cast.cs:12

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information. 

namespace System.Reactive.Linq
{
    public partial class AsyncObservable
    {
        public static IAsyncObservable<TResult> Cast<TSource, TResult>(this IAsyncObservable<TSource> source)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            return Create<TSource, TResult>(source, static (source, observer) => source.SubscribeSafeAsync(AsyncObserver.Cast<TSource, TResult>(observer)));
        }
    }

    public partial class AsyncObserver
    {
        public static IAsyncObserver<TSource> Cast<TSource, TResult>(IAsyncObserver<TResult> observer)
        {
            if (observer == null)
                throw new ArgumentNullException(nameof(observer));

            return Select<TSource, TResult>(observer, x => (TResult)(object)x);
        }
    }
}

View on GitHub (pinned to 94b5d5ab91)