Forked from coderoffortune/TryParseOrElseExtension.cs
Created
September 24, 2018 07:18
-
-
Save stramargio/f96a4393c5440bd8406f692c26411369 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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