Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stramargio/f96a4393c5440bd8406f692c26411369 to your computer and use it in GitHub Desktop.
Save stramargio/f96a4393c5440bd8406f692c26411369 to your computer and use it in GitHub Desktop.
using System;
namespace Extensions
{
public static class TryParseOrElseExtension
{
public static int TryParseOrElse(this string value, int orElse)
{
try {
return int.Parse(value);
} catch (Exception) {
return 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