Table of Contents

TypeArgumentException Class

Definition

Namespace
Cuemon
Assemblies
Cuemon.Kernel.dll
Source
src/Cuemon.Kernel/TypeArgumentException.cs

The exception that is thrown when one of the type arguments provided to a method is not valid.

public class TypeArgumentException : ArgumentException, ISerializable
Inheritance
TypeArgumentException
Implements
Inherited Members

Examples

The following example demonstrates how to throw and catch a when a generic type argument does not satisfy expected constraints at runtime.

using System;
using System.IO;
using Cuemon;

namespace Contoso.DependencyInjection;

public sealed class TypeArgumentExceptionExample
{
    public static void Run()
    {
        IDisposable disposable = Create<IDisposable, MemoryStream>();
        disposable.Dispose();

        try
        {
            Create<IDisposable, Widget>();
        }
        catch (TypeArgumentException ex)
        {
            Console.WriteLine($"{ex.ParamName}: {ex.Message}");
        }
    }

    private static TService Create<TService, TImplementation>()
        where TImplementation : class, new()
    {
        if (!typeof(TService).IsAssignableFrom(typeof(TImplementation)))
        {
            throw new TypeArgumentException(
                nameof(TImplementation),
                $"{typeof(TImplementation).Name} must implement {typeof(TService).Name}.");
        }

        return (TService)(object)new TImplementation();
    }

    private sealed class Widget
    {
    }
}

Constructors

Name Description
TypeArgumentException()

Initializes a new instance of the TypeArgumentException class.

TypeArgumentException(string)

Initializes a new instance of the TypeArgumentException class.

TypeArgumentException(string, Exception)

Initializes a new instance of the TypeArgumentException class.

TypeArgumentException(string, string)

Initializes a new instance of the TypeArgumentException class.