Type Pattern With Nullable Type - CSharp Language Basics

CSharp examples for Language Basics:Nullable

Description

Type Pattern With Nullable Type

Demo Code

using System;//from ww w  . ja v  a 2 s . com
using System.ComponentModel;
class TypePatternWithNullableType
{
   static void Main()
   {
      CheckType<int?>(null);
      CheckType<int?>(5);
      CheckType<int?>("text");
      CheckType<string>(null);
      CheckType<string>(5);
      CheckType<string>("text");
   }
   static void CheckType<T>(object value)
   {
      if (value is T t)
      {
         Console.WriteLine($"Yes! {t} is a {typeof(T)}");
      }
      else
      {
         Console.WriteLine($"No! {value ?? "null"} is not a {typeof(T)}");
      }
   }
}

Result


Related Tutorials