Click or drag to resize

TryCastExtensionTryCastTValue Method

Creates the TryCastWorkerTValue object to get a fluent notation for try-casting types.

This pattern avoids heavily nested if (class is type) / else chains when testing for more than one possible cast.

Namespace:  TomsToolbox.Desktop
Assembly:  TomsToolbox.Desktop (in TomsToolbox.Desktop.dll)
Syntax
public static TryCastWorker<TValue> TryCast<TValue>(
	this TValue value
)
where TValue : class

Parameters

value
Type: TValue
The value.

Type Parameters

TValue
The type of the value.

Return Value

Type: TryCastWorkerTValue
The TryCastWorkerTValue object.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type . When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).
Remarks
This has been somewhat superseded by the new C# language feature switch() { case Type variable: ... }, but for some complex scenarios it might still have some advantages.
Examples
C#
schedule.TryCast()
    .When<SingleSchedule>(x => x.Remove())
    .When<RecurrentSchedule>(x = > x.AddExceptionDate(date))
    .ElseThrow();
See Also