Last active
March 24, 2024 04:38
-
-
Save relyky/62963953866a0113bb546211a4281107 to your computer and use it in GitHub Desktop.
c#, is nullable, IsNullable, How to check if an object is nullable?
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
/// | |
/// How to check if an object is nullable? | |
/// ref → http://stackoverflow.com/questions/374651/how-to-check-if-an-object-is-nullable | |
/// | |
static bool IsNullable<T>(T obj) | |
{ | |
if (obj == null) return true; // obvious | |
Type type = typeof(T); | |
if (!type.IsValueType) return true; // ref-type | |
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T> | |
return false; // value-type | |
} | |
static bool IsNullable<T>() | |
{ | |
Type type = typeof(T); | |
if (!type.IsValueType) return true; // ref-type | |
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T> | |
return false; // value-type | |
} | |
//# Testing | |
Decimal C = 9; | |
Decimal? D = 9; | |
bool b1 = IsNullable(C); // false | |
bool b2 = IsNullable(D); // ture | |
bool b3 = IsNullable<Decimal>(); // false | |
bool b4 = IsNullable<Decimal?>(); // ture |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gist:
https://sharplab.io/#v2:C4LgTgrgdgNAJiA1AHwAICYCMBYAUKgBgAJVMA6AGQEsoBHAbjzwxMwHY8BvPI31gNhIAWIgFkAhjQAUpAgG0AukXFgA5gGcAlDz7dcfA0QBuKosACm64MQC8ROOYBm4iABtgUmsAD8mxvsNeEzAzS2BMIjshdH9AoNMLK3RIogAiAAlzV1cAe1TYuODQqwBmFIBRKAgAW3MwcQAjV3MycuqAB2AATwAeLwA+KT8dQKLE4BE7KHMAd1Y2IYLRhLCAVhShyP75sglpAEEweq7Wju6e2UHNYYDAkcNSAE4pAEl1ADk3V0bmqXGCa5LB6YZ5vT7ZH7mP5hTCA+4GJ6vD5fSHQpJw27A0HIiFNKHjEoYuKsbHg754tETIlxRFglEU8aram8AC+93upEEDRyOVcRDpuOaPQAKoNhUQcg0AFbaTF6YlURxEKSSqWRKZfTQkNhmSDmehEAD0holDSMVByEHU8L4qB1AvJQtFixtrI5mC5PL5DshIqu93lcWFXXa5jMIbDdm6oZyjikwpuCqVUgAhNGWm8AGriVwQczB0Nau26vMG41EMBOAC06ddREVyrJkLIAHFzMAAKpQBxgVxdGiqAv4iNalMa7JFnXAPVlk1NvF+uvF5yudT6o0mky58w1iP3Nm4A9AA===