Csharp/CSharp Tutorial/Data Type/nullable

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Age Calculation with nullable death date

<source lang="csharp">using System; using System.ruponentModel;

       class Person
       {
           DateTime birth;
           DateTime? death;
           string name;
           public TimeSpan Age{
               get{
                   if (death == null){
                       return DateTime.Now - birth;
                   }else{
                       return death.Value - birth;
                   }
               }
           }
           public Person(string name,DateTime birth,DateTime? death)
           {
               this.birth = birth;
               this.death = death;
               this.name = name;
           }
           public static void Main()
           {
               Person turing = new Person("A",new DateTime(1913, 2, 23),new DateTime(1954, 6, 7));
               Person knuth = new Person("D",new DateTime(1978, 1, 10),null);
           }
      }</source>

Box and unbox for nullable value

<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.ruponentModel;

   class MainClass
   {
       static void Main()
       {
           int? nullable = 5;
           object boxed = nullable;
           Console.WriteLine(boxed.GetType());
           int normal = (int)boxed;
           Console.WriteLine(normal);
           nullable = (int?)boxed;
           Console.WriteLine(nullable);
           nullable = new int?();
           boxed = nullable;
           Console.WriteLine(boxed == null);
           nullable = (int?)boxed;
           Console.WriteLine(nullable.HasValue);
       }
   }</source>

Boxing And Unboxing for nullable type

<source lang="csharp">using System; using System.ruponentModel;

   class MainClass
   {
       static void Main()
       {
           Nullable<int> nullable = 5;
           object boxed = nullable;
           Console.WriteLine(boxed.GetType());
           nullable = (Nullable<int>)boxed;
           Console.WriteLine(nullable);
           nullable = new Nullable<int>();
           boxed = nullable;
           Console.WriteLine(boxed == null);
           nullable = (Nullable<int>)boxed;
           Console.WriteLine(nullable.HasValue);
       }
   }</source>

Convert nullable value to string

<source lang="csharp">using System; using System.ruponentModel;

   class NullableMembers
   {
       static void Display(Nullable<int> x)
       {
           Console.WriteLine("HasValue: {0}", x.HasValue);
           if (x.HasValue)
           {
               Console.WriteLine("Value: {0}", x.Value);
               Console.WriteLine("Explicit conversion: {0}", (int)x);
           }
           Console.WriteLine("ToString(): \"{0}\"", x.ToString());
       }
       static void Main()
       {
           Nullable<int> x = 5;
           x = new Nullable<int>(5);
           Console.WriteLine("Instance with value:");
           Display(x);
           x = new Nullable<int>();
           Console.WriteLine("Instance without value:");
           Display(x);
       }
   }</source>

Does Nullable value has value

<source lang="csharp">using System; using System.ruponentModel;

   class NullableMembers
   {
       static void Display(Nullable<int> x)
       {
           Console.WriteLine("HasValue: {0}", x.HasValue);
           if (x.HasValue)
           {
               Console.WriteLine("Value: {0}", x.Value);
               Console.WriteLine("Explicit conversion: {0}", (int)x);
           }
       }
       static void Main()
       {
           Nullable<int> x = 5;
           x = new Nullable<int>(5);
           Console.WriteLine("Instance with value:");
           Display(x);
           x = new Nullable<int>();
           Console.WriteLine("Instance without value:");
           Display(x);
       }
   }</source>

Function for getting Nullable double value

<source lang="csharp">using System; public class MainClass{

       static double? GetNullableDouble()
       {
           double? result;
           string userInput = Console.ReadLine();
           try
           {
               result = double.Parse(userInput);
           }
           catch
           {
               result = null;
           }
           return result;
       }

}</source>

Get hash code for nullable value

<source lang="csharp">using System; using System.ruponentModel;

   class NullableMembers
   {
       static void Display(Nullable<int> x)
       {
           Console.WriteLine("HasValue: {0}", x.HasValue);
           if (x.HasValue)
           {
               Console.WriteLine("Value: {0}", x.Value);
               Console.WriteLine("Explicit conversion: {0}", (int)x);
           }
           Console.WriteLine("GetHashCode(): {0}", x.GetHashCode());
       }
       static void Main()
       {
           Nullable<int> x = 5;
           x = new Nullable<int>(5);
           Console.WriteLine("Instance with value:");
           Display(x);
           x = new Nullable<int>();
           Console.WriteLine("Instance without value:");
           Display(x);
       }
   }</source>

Get value or default value for nullable value

<source lang="csharp">using System; using System.ruponentModel;

   class NullableMembers
   {
       static void Display(Nullable<int> x)
       {
           Console.WriteLine("HasValue: {0}", x.HasValue);
           if (x.HasValue)
           {
               Console.WriteLine("Value: {0}", x.Value);
               Console.WriteLine("Explicit conversion: {0}", (int)x);
           }
           Console.WriteLine("GetValueOrDefault(): {0}",x.GetValueOrDefault());
           
       }
       static void Main()
       {
           Nullable<int> x = 5;
           x = new Nullable<int>(5);
           Console.WriteLine("Instance with value:");
           Display(x);
           x = new Nullable<int>();
           Console.WriteLine("Instance without value:");
           Display(x);
       }
   }</source>

Nullable Class Members

<source lang="csharp">using System; using System.ruponentModel;

   class NullableMembers
   {
       static void Display(Nullable<int> x)
       {
           Console.WriteLine("HasValue: {0}", x.HasValue);
           if (x.HasValue)
           {
               Console.WriteLine("Value: {0}", x.Value);
               Console.WriteLine("Explicit conversion: {0}", (int)x);
           }
       }
       static void Main()
       {
           Nullable<int> x = 5;
           x = new Nullable<int>(5);
           Console.WriteLine("Instance with value:");
           Display(x);
           x = new Nullable<int>();
           Console.WriteLine("Instance without value:");
           Display(x);
       }
   }</source>

Nullable integer Demo

<source lang="csharp">using System; using System.ruponentModel;

   class NullableDemo
   {
       static void Main()
       {
           int? x = null;
           x = 5;           
           if (x != null)           
           {
               int y = x.Value;      
               Console.WriteLine (y);
           }
           int z = x ?? 10;
       }
   }</source>

Nullable Try Parse

<source lang="csharp">using System; using System.ruponentModel;

   class NullableTryParse
   {
       static int? TryParse(string data)
       {
           int ret;
           if (int.TryParse(data, out ret))
           {
               return ret;
           }
           else
           {
               return null;
           }
       }
       static void Main()
       {
           int? parsed = TryParse("Not valid");
           if (parsed != null)
           {
               Console.WriteLine("Parsed to {0}", parsed.Value);
           }
           else
           {
               Console.WriteLine("Couldn"t parse");
           }
       }
   }</source>

Nullable value based vector

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text;

   public class Vector
   {
       public double? R = null;
       public double? Theta = null;
       public double? ThetaRadians
       {
           get
           {
               return (Theta * Math.PI / 180.0);
           }
       }
       public Vector(double? r, double? theta)
       {
           if (r < 0){
               r = -r;
               theta += 180;
           }
           theta = theta % 360;
           R = r;
           Theta = theta;
       }
       public static Vector operator +(Vector op1, Vector op2)
       {
           try
           {
               double newX = op1.R.Value * Math.Sin(op1.ThetaRadians.Value)+ op2.R.Value * Math.Sin(op2.ThetaRadians.Value);
               double newY = op1.R.Value * Math.Cos(op1.ThetaRadians.Value)+ op2.R.Value * Math.Cos(op2.ThetaRadians.Value);
               double newR = Math.Sqrt(newX * newX + newY * newY);
               double newTheta = Math.Atan2(newX, newY) * 180.0 / Math.PI;
               return new Vector(newR, newTheta);
           }
           catch
           {
               return new Vector(null, null);
           }
       }
       public static Vector operator -(Vector op1)
       {
           return new Vector(-op1.R, op1.Theta);
       }
       public static Vector operator -(Vector op1, Vector op2)
       {
           return op1 + (-op2);
       }
       public override string ToString()
       {
           string rString = R.HasValue ? R.ToString() : "null";
           string thetaString = Theta.HasValue ? Theta.ToString() : "null";
           return string.Format("({0}, {1})", rString, thetaString);
       }
   }
   class Program
   {
       static void Main(string[] args)
       {
           Vector v1 = new Vector(1, 2);
           Vector v2 = new Vector(1, 3);
           Console.WriteLine("{0} + {1} = {2}", v1, v2, v1 + v2);
           Console.WriteLine("{0} - {1} = {2}", v1, v2, v1 - v2);
       }
   }</source>

Partial Comparer for nullable value

<source lang="csharp">using System.Collections.Generic; using System.ruponentModel;

   public static class PartialComparer
   {
       public static int? Compare<T>(T first, T second)
       {
           return Compare(Comparer<T>.Default, first, second);
       }
       public static int? Compare<T>(IComparer<T> comparer,T first,T second)
       {
           int ret = comparer.rupare(first, second);
           if (ret == 0)
           {
               return null;
           }
           return ret;
       }
   }</source>

Provide default value for nullable value

<source lang="csharp">using System; using System.ruponentModel;

   class NullableMembers
   {
       static void Display(Nullable<int> x)
       {
           Console.WriteLine("HasValue: {0}", x.HasValue);
           if (x.HasValue)
           {
               Console.WriteLine("Value: {0}", x.Value);
               Console.WriteLine("Explicit conversion: {0}", (int)x);
           }
           Console.WriteLine("GetValueOrDefault(10): {0}",x.GetValueOrDefault(10));            
       }
       static void Main()
       {
           Nullable<int> x = 5;
           x = new Nullable<int>(5);
           Console.WriteLine("Instance with value:");
           Display(x);
           x = new Nullable<int>();
           Console.WriteLine("Instance without value:");
           Display(x);
       }
   }</source>

Reference Compare for nullable value

<source lang="csharp">public static class PartialComparer

   {
       public static int? ReferenceCompare<T>(T first, T second) where T : class{
           if (first == second){
               return 0;
           }
           if (first == null){
               return -1;
           }
           if (second == null){
               return 1;
           }
           return null;
       }
   }</source>

Using the Nullable Modifier

<source lang="csharp">public class MainClass{

   static void Main()
   {
     int? count = null;
     do
     {
         // ...
     }
     while(count == null);
   }

}</source>