Nullable Type In C# with Example


IN THIS  POST WE WILL LEARN 



  1. NULLABLE TYPE IN C# 
  2. NULL COALESCING  OPERATOR  ??  


Type in C#

In C# types are divided into 2 broad Categories

Reference Types :  Interface , Class , Delegates , Arrays E.t.c
Value Types        : Int , Float , Double , Structs ,Enums E.t.c

By Default value types are non nullable. To make then nullable Use   ?

int r= 0 (r is non nullable, so r cannot be set null , r= null will generate Error )

int? m =0 (m is nullable int , so m=null is legal)


Example :  Nullable Type  In C#


  1. using System;


  2. namespace NullableTypeInCshape
  3. {
  4.     class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {

  8.             bool? AreYouvirgin = true;

  9.             if (AreYouvirgin ==true)
  10.             {
  11.                 Console.WriteLine("Yes I am virgin ");
  12.                 
  13.             }
  14.             else if (AreYouvirgin == false)
  15.             {
  16.                  Console.WriteLine("Yes I am Not virgin  "); 
  17.             }
  18.             else
  19.             {
  20.                 Console.WriteLine(" Use Can Not Given Answer");

  21.             }

  22.             Console.ReadLine();
  23.         }
  24.     }
  25. }
         Output :




2. NULL COALESCING  OPERATOR  ??  


 Example :   With Out Null Coalescing Operator
  • using System;


  • namespace NullableTypeInCshape
  • {
  •     class Program
  •     {
  •         static void Main(string[] args)
  •         {

  •             int? RoomOnSale = null;
  •             int AvaialableRoom;

  •             if (RoomOnSale ==null)
  •             {
  •                 AvaialableRoom = 0; 
  •             }
  •             else
  •             {
  •                 AvaialableRoom = RoomOnSale.Value;
  •             }
  •             Console.WriteLine("AvaialableRoom={0}", AvaialableRoom);


  •         }
  •     }
  • }




  •  Example :  Using  Null Coalescing Operator


  • using System;


  • namespace NullableTypeInCshape
  • {
  •     class Program
  •     {
  •         static void Main(string[] args)
  •         {

  •             int? RoomOnSale = null;
  •             int AvaialableRoom = RoomOnSale ??0;//  Using sing  Null Coalescing Operator 

  •            
  •             Console.WriteLine("AvaialableRoom={0}", AvaialableRoom);

  •             Console.ReadLine();

  •         }
  •     }
  • }


  • Output:
     







    Comments

    Popular posts from this blog

    CREATING INTERNET APPLICATION PROJECT & MVC USING DATA BASE FIRST APPROACH

    Real Time Example add dynamic fields using jquery looking Treeview

    How to create DATA BASE And Tables in MSSQL Server

    Data Type Conversions in C# with real time example

    Basic -C# Reading and writing to a console