Skip to content

Instantly share code, notes, and snippets.

@coderoffortune
Last active October 26, 2018 13:29
Show Gist options
  • Save coderoffortune/44c0528ef06c3e60f11d3e602a5f9ae2 to your computer and use it in GitHub Desktop.
Save coderoffortune/44c0528ef06c3e60f11d3e602a5f9ae2 to your computer and use it in GitHub Desktop.
namespace Extensions
{
public static class TryParseOrElseExtension
{
public static int TryParseOrElse(this string value, int orElse)
{
return int.TryParse(value, out int result) ? result : orElse;
}
}
}
using NUnit.Framework;
using Extensions;
[TestFixture]
public class TryParseOrElseExtensionTest
{
[Test]
public void ShouldReturnTheValueIfTheStringIsAValidNumber()
{
int result = "10".TryParseOrElse(1);
Assert.IsTrue(result == 10);
}
[Test]
public void ShouldReturnOrElseValueIfTheStringIsNotAValidNumber()
{
int result = "whatever".TryParseOrElse(100);
Assert.IsTrue(result == 100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment