Created
November 15, 2011 03:07
-
-
Save ijoyce/1366016 to your computer and use it in GitHub Desktop.
GetOrElse extension method for c#
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 GetOrElse | |
{ | |
public static class GetOrElseExtension | |
{ | |
public static T GetOrElse<T>(this Nullable<T> instance, T orElse) where T: struct | |
{ | |
if (instance == null) | |
return orElse; | |
return instance.Value; | |
} | |
} | |
} |
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 GetOrElse | |
{ | |
class MainClass | |
{ | |
public static void Main (string[] args) | |
{ | |
Nullable<int> i = null; | |
Console.WriteLine(i.GetOrElse<int>(5)); | |
int? j = 42; | |
Console.WriteLine(j.GetOrElse<int>(12)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same as GetValueOrDefault() I guess.