Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions src/SmartEnum/SmartEnum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -266,20 +266,34 @@ public static TEnum FromValue(TValue value, TEnum defaultValue)
/// When this method returns, contains the item associated with the specified value, if the value is found;
/// otherwise, <c>null</c>. This parameter is passed uninitialized.</param>
/// <returns>
/// <c>true</c> if the <see cref="SmartEnum{TEnum, TValue}"/> contains an item with the specified name; otherwise, <c>false</c>.
/// <c>true</c> if the <see cref="SmartEnum{TEnum, TValue}"/> contains an item with the specified value; otherwise, <c>false</c>.
/// </returns>
/// <seealso cref="SmartEnum{TEnum, TValue}.FromValue(TValue)"/>
/// <seealso cref="SmartEnum{TEnum, TValue}.FromValue(TValue, TEnum)"/>
public static bool TryFromValue(TValue value, out TEnum result)
#nullable enable
public static bool TryFromValue(TValue? value, [NotNullWhen(true)] out TEnum? result)
{
if (value is null)
if (value is not null)
{
result = default;
return false;
if (_fromValue.Value.TryGetValue(value, out var resolvedValue))
{
result = resolvedValue!;
return true;
}
}
else
{
result = _enumOptions.Value.FirstOrDefault(x => x.Value is null);
if (result != null)
{
return true;
}
}

return _fromValue.Value.TryGetValue(value, out result);
result = null;
return false;
}
#nullable restore

/// <summary>
///
Expand Down
53 changes: 53 additions & 0 deletions test/SmartEnum.UnitTests/SmartEnumTryFromValue.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
namespace Ardalis.SmartEnum.UnitTests
{
using FluentAssertions;
using Xunit;

public class SmartEnumTryFromValue
{
[Fact]
public void ReturnsTrueAndEnumGivenMatchingValue()
{
var result = TestEnum.TryFromValue(1, out var output);

result.Should().BeTrue();
output.Should().BeSameAs(TestEnum.One);
}

[Fact]
public void ReturnsFalseAndNullGivenNonMatchingValue()
{
var result = TestEnum.TryFromValue(-1, out var output);

result.Should().BeFalse();
output.Should().BeNull();
}

[Fact]
public void ReturnsFalseAndNullGivenNullStringValue()
{
var result = TestStringEnum.TryFromValue(null, out var output);

result.Should().BeFalse();
output.Should().BeNull();
}

[Fact]
public void ReturnsTrueAndEnumGivenMatchingStringValue()
{
var result = TestStringEnum.TryFromValue(nameof(TestStringEnum.One), out var output);

result.Should().BeTrue();
output.Should().BeSameAs(TestStringEnum.One);
}

[Fact]
public void ReturnsTrueAndEnumGivenMatchingNullValue()
{
var result = TestNullableStringEnum.TryFromValue(null, out var output);

result.Should().BeTrue();
output.Should().BeSameAs(TestNullableStringEnum.None);
}
}
}