Skip to content

Instantly share code, notes, and snippets.

@izackp
Last active July 2, 2020 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izackp/fcff42455a63093805b3b055f5707b21 to your computer and use it in GitHub Desktop.
Save izackp/fcff42455a63093805b3b055f5707b21 to your computer and use it in GitHub Desktop.
Needed a one liner guard function for C# that doesn't thrown an exception.
/*
Example Usage:
public int CalcScore(VideoResolution? itemResolution) {
if (Util.Guard(out VideoResolution res, itemResolution)) return 0;
if (res == VideoResolution._1080p) return 5;
return 1;
}
Alternatively you can do:
if (!(itemResolution is VideoResolution res)) return 0;
in C#9:
if (itemResolution is not VideoResolution res) return 0;
*/
public static class Util {
public static bool Guard<T>(out T target, T? source) where T: class {
if (source == null) {
target = null;
return true;
}
target = source;
return false;
}
public static bool Guard<T>(out T target, T? source) where T: struct {
if (source == null) {
target = default(T);
return true;
}
target = (T)source;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment