// Simple successful resultvarsuccessResult=Result<string>.Success("Operation successful");// Valued successful resultvaruserResult=Result<User>.Success(newUser{Id=1,Name="John"});// Nullable value to resultstring?name="John";varnameResult=name.ToResult("Name cannot be null");// Value with validationvarageResult=25.ToResult(age=>age>=18,"Age must be at least 18");
// Simple errorvarerrorResult=Result<string>.Failure("An error occurred");// Coded errorvarnotFoundResult=Result<User>.Failure(ErrorCode.NotFound,"User not found");// Detailed error with metadatavarvalidationError=Result<User>.Failure(ErrorCode.ValidationError,"Invalid user information",newDictionary<string,object>{{"Field","Email"},{"Value","invalid-email"},{"Timestamp",DateTime.UtcNow}});// From exceptiontry{// Some operation that might throw}catch(Exceptionex){varerrorResult=Result<int>.Failure(Error.FromException(ex,ErrorCode.InvalidOperation));}
// Using CatchvarrecoveredResult=result.Catch(error=>{if(error.Code==ErrorCode.NotFound){returnResult<T>.Success(GetDefaultValue());}returnResult<T>.Failure(error);});// Using Catch with predicatevarspecificRecovery=result.Catch(error=>error.Code==ErrorCode.ValidationError,error=>Result<T>.Success(GetDefaultValue()));
// Get value or defaultvarvalue=result.GetValueOrDefault("default");// Get value or execute functionvarvalue=result.GetValueOr(()=>GetDefaultValue());// Get value or throwtry{varvalue=result.GetValueOrThrow();}catch(Exceptionex){// Handle exception}// Get value or throw custom exceptionvarvalue=result.GetValueOrThrow(error=>newCustomException(error.Message));
// Get value or default asyncvarvalue=awaitresult.GetValueOrAsync(async()=>awaitGetDefaultValueAsync());// Get value or execute async functionvarvalue=awaitresult.GetValueOrAsync(asyncerror=>awaitHandleErrorAsync(error));
// Single conditionvarvalidatedResult=result.Validate(value=>value!=null,"Value cannot be null");// Multiple conditionsvarmultiValidatedResult=result.Validate(value=>new[]{(value!=null,"Value cannot be null"),(value.Length>0,"Value length must be greater than 0")});