Check if property is either of type or it's nullable type

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Check if property is either of type or it's nullable type



I am currently checking if a property type is either a DateTime or a nullable DateTime like this:


if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))



Can anyone please tell me if I can somehow condense this into a single statement by checking the underlying type?





Have a look at this post. Answers your question.
– Dimith
Aug 13 at 3:58




3 Answers
3



Here is a simple sollution: typeof(DateTime?).IsAssignableFrom(prop.PropertyType). This will be true for DateTime? or DateTime and false for others.


typeof(DateTime?).IsAssignableFrom(prop.PropertyType)


DateTime?


DateTime





Thanks Vasily, though I want to true if it is EITHER DateTime OR DateTime? I don't want to know if it is nullable or not.
– Cameron Forward
Aug 13 at 5:29





@CameronForward, I see now. Can you check new version?
– vasily.sib
Aug 13 at 5:41



You may try this:


if (prop.PropertyType.UnderlyingSystemType==typeof(DateTime))



...





Thanks Mohammad but this doesn't pick up the nullable struct unfortunately
– Cameron Forward
Aug 13 at 5:28



Try something like this


public class Program

public static void Main(string args)

//Your code goes here
DateTime? nullableDate = null;

bool output = CheckNull.IsNullable(nullableDate); // false

Console.WriteLine(output );


public static class CheckNull

public static bool IsNullable<T>(T t) return false;
public static bool IsNullable<T>(T? t) where T : struct return true;




output : True


True






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS