Last active
July 2, 2020 04:37
Needed a one liner guard function for C# that doesn't thrown an exception.
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
/* | |
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