locked
How to check if object value is Null and if null assign NULL to type datetime RRS feed

  • Question

  • Dear Experts,

    I'm passing a object value to the function and I can pass only value if the object value is null it throws exception. How to check if object value is null, if null assign null else pass the object as datetime value?

     

    public string FamCode { get; set; }
            public string EnvironmentNo { get; set; }
            public DateTime StockingDate { get; set; }
    
     public UntaggedStockCommEnvi(string famcde,string envino, object stckdte,string initstck,string recby)
            {
                FamCode = famcde;
    
                EnvironmentNo = envino;
    
                StockingDate = Convert.ToDateTime(stckdte);
                //DateTime.ParseExact(stckdte, "dd/MM/yyyy", CultureInfo.InvariantCulture);
    
    }
    StockingDate = (String.IsNullOrEmpty(stckdte.ToString()) ? (DateTime?)null : Convert.ToDateTime(stckdte)(stckdte));

    I have tried the above way but hard to understand the syntax for datetime.

    Thanks fro any advice

    NewB


    NewBInVB

    Wednesday, February 28, 2018 3:09 PM

Answers

  • If you want to convert an object to a DateTime then Convert.ToDateTime will already handle null. It returns DateTime.MinValue.

    StockingDate = Convert.ToDateTime(stckdte);
    But you said you wanted null if the value was null. That isn't going to work because your StockingDate property is defined as DateTime and DateTime cannot be null. If the date is optional then you'll need to change the property type to DateTime? Then you can handle the null check before the conversion.

    public DateTime? StockingDate { get; set; }
    
    //Later in the code
    StockingDate = (stckdte != null) ? Convert.ToDateTime(stckdte) : null;
    
    //Or a simple if statement
    if (stckdte != null)
       StockingDate = Convert.ToDateTime(stckdte);


    Michael Taylor http://www.michaeltaylorp3.net

    • Proposed as answer by Fei Hu Thursday, March 1, 2018 2:25 AM
    • Marked as answer by NewBInCoding Thursday, March 1, 2018 2:22 PM
    Wednesday, February 28, 2018 6:16 PM

All replies

  • Why using object as parameter??

    e.g.

    public class UntaggedStockCommEnvi
    {  
      public string FamCode { get; set; }
      public string EnvironmentNo { get; set; }
      public DateTime StockingDate { get; set; }
    
      // using overloads
      public UntaggedStockCommEnvi(string famcde, string envino, DateTime stckdte)
      {
    	this.FamCode = famcde;
    	this.EnvironmentNo = envino;
    	this.StockingDate = stckdte;
      }
    
      public UntaggedStockCommEnvi(string famcde, string envino)
      {
    	this.FamCode = famcde;
    	this.EnvironmentNo = envino;	
      }
      
      // or nullable parameters
      public UntaggedStockCommEnvi(string famcde, string envino, DateTime? stckdte)
      {
    	this.FamCode = famcde;
    	this.EnvironmentNo = envino;
    	if (stckdte.HasValue)
    	{
    	  this.StockingDate = stckdte.Value;
    	}
      }  
    }  

    Wednesday, February 28, 2018 3:28 PM
  • If you want to convert an object to a DateTime then Convert.ToDateTime will already handle null. It returns DateTime.MinValue.

    StockingDate = Convert.ToDateTime(stckdte);
    But you said you wanted null if the value was null. That isn't going to work because your StockingDate property is defined as DateTime and DateTime cannot be null. If the date is optional then you'll need to change the property type to DateTime? Then you can handle the null check before the conversion.

    public DateTime? StockingDate { get; set; }
    
    //Later in the code
    StockingDate = (stckdte != null) ? Convert.ToDateTime(stckdte) : null;
    
    //Or a simple if statement
    if (stckdte != null)
       StockingDate = Convert.ToDateTime(stckdte);


    Michael Taylor http://www.michaeltaylorp3.net

    • Proposed as answer by Fei Hu Thursday, March 1, 2018 2:25 AM
    • Marked as answer by NewBInCoding Thursday, March 1, 2018 2:22 PM
    Wednesday, February 28, 2018 6:16 PM
  • Hey CoolDadTx,

     I got a question, is the internal mechanics of Type Null functionally the

    same as Box/UnBox without the need for NullRef error catching?

     

     I tried out the idea of the OP using Dynamic and base Type Object. Boxing

    works but Null variables are not defined and without Type. So, usage was

    evaluate for Null before boxing. 

     

     Runtime Boxing Code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication23
    {
        class Program
        {
            static void Main( string[] args )
            {
                Console.WriteLine( "Runtime Boxing\n" );
    
                dynamic dt = null;
    
                Console.Write( "Code: dynamic dt = null; \t" );
    
                Console.WriteLine( "// {0}\n", ( dt != null ? String.Format( "Type is {0}", dt.GetType().ToString() ) : "Null (undefined Type)" ) );
    
                if ( dt == null )
                {
                    dt = ( DateTime ) DateTime.Now;
                }
                
                Console.WriteLine( "Code: if ( dt == null )" );
                Console.WriteLine( "      {" );
                Console.Write( "          dt = ( DateTime ) DateTime.Now;\t" );
                Console.WriteLine( "// {0}\n", ( dt != null ? String.Format( "Type is {0}", dt.GetType().ToString() ) : "Null (undefined Type)" ) );
                Console.WriteLine( "      }\n" );
    
                if ( dt != null )
                {
                    dt = null;
                }
    
                Console.WriteLine( "Code: if ( dt != null )" );
                Console.WriteLine( "      {" );
                Console.Write( "          dt = null;\t" );
                Console.WriteLine( "// {0}\n", ( dt != null ? String.Format( "Type is {0}", dt.GetType().ToString() ) : "Null (undefined Type)" ) );
                Console.WriteLine( "      }\n" );
    
                Console.ReadLine();
            }
        }
    }
     Any thoughts? Thanks
    Wednesday, February 28, 2018 9:37 PM
  • I'm not sure I'm following what you're saying. There isn't a Null type in .NET.

    Boxing is the process of converting a value type to an object. So this wouldn't have anything to do with null since a value type cannot be null (ignoring Nullable<T>). Boxing null wouldn't make sense as it is already a ref type (effectively). Boxing requires that the runtime allocate an actual object in memory and then pushing the value into it. This is actually handled in the CLR in a couple of different ways but the simplified approach calls the box instruction to create the object and mem copy the value object into it. The full details of how this works is somewhat undocumented but you can google for some blog articles on the currently behavior.

    The dynamic keyword ultimately relies on the DLR to wrap an object. It has higher overhead than normal types because it's members dynamically adjust. So doing something as simple as referencing a property involves more runtime code. Basically everything is late bound via the IDynamicMetaObjectProvider. I wouldn't recommend using dynamic in most cases and certainly not for working with value types. But again I'm not sure where you're going with your discussion.

    Looking at your code, you are creating a dynamic object and then assigning a value type to it. That would trigger a boxing operation on the DateTime. While the runtime will query for that property and find out it is a DateTime, the value still has to be stored. I haven't looked but I suspect that the dynamic C# keyword probably ends up mapping to the ExpandoObject type. That type uses (I believe) a dictionary under the hood and, since any type can be stored, would have to map the value to object. So values types are going to be boxed going in and unboxed coming out. That's a pretty high overhead for just a null check.

    Ultimately a null check is going to be fastest because Equals implementations should first check for null. More importantly though there isn't any boxing nor is there any memory allocs that need to occur. For a value type the compiler can optimize away a null check because value types cannot be null. For comparisons to other values there would be a boxing operation for comparison with the default Equals method. But one of the rules around creating value types is that you should implement IEqualityComparer<T> (which provides a generic implementation to avoid the boxing). Additionally the C# == and != operators are generally implemented to call the generic version as well. 

    If you need to convert a value type to an object then you really cannot avoid boxing. The perfect world would be to use strong types when possible and nullable value types (DateTime?) when not. Conversion to object should be a last resort.


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, February 28, 2018 10:57 PM
  • CoolDadTx,

     Yeah, I figured the overhead was much. I always keep to Strongly

    Typed object vs anything else or surprise results in my code. Good

    information.

     Thanks :)

    Wednesday, February 28, 2018 11:47 PM