ThrowNewForAttribute Class

Specifies that the source generator of L.o.U.I.S. adds ThrowNew extension methods for an exception type to the static class that has the attribute.

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class ThrowNewForAttribute : Attribute

Remarks

Use this attribute for an exception type that you cannot change, such as a type of another assembly. For an exception class of your own project, use ThrowNewAttribute.

For each public constructor of the exception type, the source generator adds two static extension methods to the class. Both methods have the parameters of the constructor, and throw a new instance of the exception type. Call them on the exception type, as in JsonException.ThrowNew(message).

The first method returns no value. Call it as a statement.

The second method has a type parameter, which is also its return type. Call it where the code needs an expression of that type.

The methods are internal, unless ThrowNewForAttribute.Public is true. When two assemblies have public ThrowNew methods for one exception type, a call is ambiguous in a project that references both.

The class must be static and partial, and must be neither nested nor generic. A class holds the methods of one exception type.

The exception type must not be abstract, and must have at least one public constructor. A constructor with a parameter of a pointer type gets no method.

The code that the source generator adds needs C# 14 or later.

Example

The following code declares ThrowNew methods for an exception type of the base class library, and throws an instance of it:

[ThrowNewFor(typeof(JsonException))]
internal static partial class JsonExceptionExtensions;

// As a statement
JsonException.ThrowNew("The document has no root object.");

// In an expression
return root ?? JsonException.ThrowNew<JsonObject>("The document has no root object.");

See also

Inheritance
Attribute ThrowNewForAttribute

Constructors

NameDescription
ThrowNewForAttribute(Type)Initializes a new instance of the ThrowNewForAttribute class.

ThrowNewForAttribute(Type)

Initializes a new instance of the ThrowNewForAttribute class.

public ThrowNewForAttribute(Type exceptionType)

Parameters

exceptionType Type
The exception type that gets the ThrowNew methods.

Properties

NameDescription
ExceptionTypeGets the exception type that gets the ThrowNew methods.
PublicGets or sets a value indicating whether the ThrowNew methods are public.

ExceptionType

Gets the exception type that gets the ThrowNew methods.

public Type ExceptionType { get; }

Property value

Type

Public

Gets or sets a value indicating whether the ThrowNew methods are public.

public bool Public { get; set; }

Property value

bool true if the methods are public; false if they are internal. The default is false.