ADO.Net rounding the DateTime parameter

I have been trying to debug a bug that was causing the records being returned out of the date window. It took me some time to realize that ADO.Net was rounding the C# DateTime and that was causing the invalid records to be returned.

My table looks somewhat like this:

blogpost1

and the code was:

using (SqlConnection conn = new SqlConnection("server=localhost\\SQLExpress;Database=TestDB;Trusted_Connection=True"))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM MyTestTable WHERE CreatedAt <= @dateTimeParameter", conn))
{
if(conn.State != ConnectionState.Open) conn.Open();
DateTime dtParameter = new DateTime(2017,03,20);
dtParameter = dtParameter.AddDays(1).AddTicks(-1); //The last moment on particular date
cmd.Parameters.Add(new SqlParameter("@dateTimeParameter", SqlDbType.DateTime) {Value = dtParameter});
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
}

With this code in place, I was trying to get the records for the last moment on March 20th. I ended up using the following code to get the last moment on the particular date.

DateTime dtParameter = new DateTime(2017,03,20);
dtParameter = dtParameter.AddDays(1).AddTicks(-1);

But when this code was executed, I got the records for the next day as well, which was clearly not intended. I tried SqlDateTime type as parameter, but it still had the same effect.

 var sqlDateTime = new SqlDateTime(dtParameter);
 cmd.Parameters.Add(new SqlParameter("@dateTimeParameter", SqlDbType.DateTime) { Value = sqlDateTime });

One thing I noticed using SqlDateTime is that the Ticks rounded to 636256512000000000 from 636256511999999999, during the conversion.

This forced me to look at the reference code for SqlDateTime, the constructor called method to get SqlDateTime from DateTime, at the end of method chain, I found the method with the following comment

// Convert from TimeSpan, rounded to one three-hundredth second, due to loss of precision
        private static SqlDateTime FromTimeSpan(TimeSpan value) {

This was the reason the DateTime was getting rounded to the next day. The fix was to use Milliseconds to get the last moment of the day. Even passing a single millisecond wasn’t enough , I had to use 2.

   dtParameter = dtParameter.AddDays(1).AddMilliseconds(-2);

This fixed the issue and I was able to get the records for the date window.

Advertisements

C# – There is no “Pass by Reference” without ref keyword

One common question that I see on Stack Overflow is about parameter passing in C#. A common statement for parameter passing sounds like:

Reference types are passed by reference and value types are passed by value

This is incorrect.

Before jumping on the details for parameter passing, I would ask you to visit this excellent article by Jon Skeet on parameter passing in C#. 

I will concentrate on parameter passing with reference types, as this is the main reason for confusion.

Consider the following example

using System;
namespace TestApplication
{
	class Program
	{
		static void Main(string[] args)
		{
			Person personMain = new Person { Name = "X", Id = 1 };
			ModifyPersonObject(personMain);
			Console.WriteLine(personMain.Name);	// prints "New Person Name"

			ModifyPersonObjectFail(personMain);
			Console.WriteLine(personMain.Name);	// still prints "New Person Name"

			Console.ReadLine();
		}

		static void ModifyPersonObject(Person person)
		{
			person.Name = "New Person Name";
		}

		static void ModifyPersonObjectFail(Person person)
		{
			person = new Person { Name = "Some Name", Id = 2 };
		}
	}

	class Person
	{
		public int Id { get; set; }
		public string Name { get; set; }
	}

}

In the above code a person object is created with initial values as “Name: X and Id: 1”. Then a method is called which is suppose to modify that person object. That method receives a paramter of type “Person” and modifies its Name property. The effect is visible after the call to method is completed.

Next, that object is send to another method which is suppose to assign a completely new “Person” object to it. But that fails and after the call to “ModifyPersonObjectFail” method is completed, the object “personMain” is still holding hold values.

Why is this happening.

A reference is kind of a pointer to some memory location holding the actual data. For example in our above code “personMain” is a reference which is pointing to a person object in memory with values Name: X and Id: 1. So in the first method call: “ModifyPersonObject(personMain);”, the parameter in the method is pointing to same memory location.

Step1

So, both “personMain” and “person” (parameter) are pointing to same location, thus changing “Name” property in the method actually modifies the value in object storage memory. .

Next is the method call to “ModifyPersonObjectFail(personMain);”, At the entry point in the method, both “personMain” and paramter “person” is pointing to same object, just like the diagram above, but this method has a line:

person = new Person { Name = "Some Name", Id = 2 };

which is assigning a new object to the parameter “person”. Now here is the important part, this line is actually creating a new object in object storage memory and assigning its address/reference  to the parameter. The original object in memory remains unaffected.

step2

Therefore, when the call to method “ModifyPersonObjectFail” is completed the original object in the caller remains unaffected.

So to conclude here is the main statement

There is no pass by reference in C# without “ref” keyword. In parameter passing address of the object (or reference) is only passed.

If you have method like:

static void ModifyPersonObjectByReference(ref Person person)
{
	person = new Person { Name = "Some Name", Id = 2 };
}

and then call that method like:

static void ModifyPersonObjectByReference(ref Person person)
{
	ModifyPersonObjectByReference(ref personMain);
}

then this would be somewhat pure pass by reference, as now even assigning a new value to parameter would be visible in caller.

C# 6.0 – Changes in New Features

(The Roslyn project and documentation has been moved to GitHub)

C# 6.0 is the new upcoming version of C#, it is part of open source compiler platform (Roslyn) by Microsoft. The new compiler is written in C# as well, (How is that possible see this and this)

There are many new features which are planned to be released with the new version, One can find the detailed documentation about them here.

Here are few which have changed from their initial planned version.

Static Import

This feature allows a user to access (allowable) static members of a class/type, without a qualifying class name.

Consider the example of

Console.WriteLine("Some test message");

With the static import, we would be able to to call method “WriteLine” directly without using the class name “Console”.

The current version of C# 6.0 supports Static Import but with the explicit keyword “static” in “using” statement.

using static System.Console;
namespace TestApplication
{
	class Program
	{
		static void Main(string[] args)
		{
			WriteLine("My test message");
		}
	}
}

 The previous planned version for C# 6.0 had static import feature without “static” keyword in using directive.  

“static import” feature might case a breaking change in very rare situation. Consider the following example with respect to “Extension Methods”

Consider the following code example in prior version of C#.

List<int> myList = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
var query = Enumerable.Where(myList, r => r % 2 == 0);

In the code above extension method “Where” is called like a static method, instead of like an instance method on “Enumerable<T>”

But if we use “static” import feature, one would thought that we should be able to do something like:

using static System.Linq.Enumerable;
//.... class definition 
List<int> myList = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
var query = Where(myList, r => r % 2 == 0); //ERROR! 

But it will error out with

The name ‘Where’ does not exist in the current context

Since “Where” is defined as an extension method. But using “Enumerable.Range” like below will not cause any error as “Range” is an ordinary static method and not an extension method. :

var items = Enumerable.Range(0, 10);
var items2 = Range(0, 10);

So now changing an ordinary static method to extension method could cause a breaking change, which wasn’t the case with prior versions of C#.

Null-Conditional Operator

Only the name/term has been changed, earlier version had Null Propagation operator. The feature is useful in a way that it provides a safe navigation operator on an object properties in case of the object being null.

int[] myArray = null;
//...some code
int? length = myArray?.Length;