Skip to content

Instantly share code, notes, and snippets.

@ijoyce
Created November 15, 2011 03:07
Show Gist options
  • Save ijoyce/1366016 to your computer and use it in GitHub Desktop.
Save ijoyce/1366016 to your computer and use it in GitHub Desktop.
GetOrElse extension method for c#
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;
}
}
}
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));
}
}
}
@ijoyce
Copy link
Author

ijoyce commented Nov 15, 2011

Same as GetValueOrDefault() I guess.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment