C# 6.0 and 7.x posts links

Hello All,

There are rapid changes to C# language recently. Although these are very useful in writing cleaner, concise, less repetitive and performance oriented code, I see very less usage of these in our day to day coding. So I thought of writing these features as blog posts to learn myself and share with others. In this post I am just listing down the links of my earlier C#6.0 and C# 7.x blog posts so that it is easily available. Do let me know if there is any important feature that I missed which could be useful in our day to day coding.

C# 6.0 features

C# 7.X features

Hope you’ll enjoy these posts and able to use these in your day to day development.

Cheers,
Brij

TransactionScope: A simple way to handle transactions in .NET

Have you ever tried implementing transactions using C# code? Normally, we implement transactions in SQL where multiple Insert/Update statements takes part in it. A Transaction follows the ACID (Atomicity, Consistency, Isolation, Durability) rule where either all the statements get committed or all get canceled and rolled back. TransactionScope allows us to implement it at application level. There could be some scenarios where you are required to do different operations in the same database or even multiple databases (distributed transaction) or due to some other constraints, it cannot be done at database level. It is also very helpful for application developers if they have less exposure to database.

What is TransactionScope

TransactionScope got introduced with .NET 2.0 as part of  System.Transaction. It is a class which provides a simple way to make a set of operations as part of a transaction without worrying about the complexity behind the scene. If any of the operation fails in between, entire transaction would fail and rolled back  which undo all the operation that got completed. All this would be taken care by the framework, ensuring the data consistency.

How to use the TransactionScope?

To use this, you need to add the reference of System.Transactions reference which is part of framework libraries (normally it wont be added by default). Once it get added, add the namespace System.Transactions wherever we want to use this. The syntax would look as

try
{
    using (TransactionScope scope = new TransactionScope())
    {
        // Do Operation 1
        // Do Operation 2
        //...

        // if all the coperations complete successfully, this would be called and commit the trabsaction. 
        // In case of an exception, it wont be called and transaction is rolled back
        scope.Complete();
    }
}
catch (ThreadAbortException ex)
{
    // Handle exception
}

Here we can see that we have used Disposable block while creating instance of TransactionScope, it makes sure the dispose gets called when it gets out of the block and ends the transaction scope.

In one Transaction scope, we can do multiple operation connecting to different databases as

using (TransactionScope scope = new TransactionScope())
{
    using (con = new SqlConnection(conString1))
    {
        con.Open();

        // Do Operation 1
        // Do Operation 2
        //...
    }

    using (con = new SqlConnection(conString2))
    {
        con.Open();

        // Do Operation 1
        // Do Operation 2
        //...

    }

    scope.Complete();
}

Here we are using two connection strings to connection different databases. We can use as many based on our requirement. We can have nested transactions as well. It could be as

public void DoMultipleTransaction()
{       
    try
    {
        using (TransactionScope scope = new TransactionScope())
        {
            using (con = new SqlConnection(conString1))
            {
                con.Open();
                // Do Operation 1
            }

            OtherTransaction();
            scope.Complete();
        }
    }
    catch (ThreadAbortException ex)
    {
        // Handle exception
    }
}

private void OtherTransaction()
{
    using (TransactionScope scope = new TransactionScope())
    {
        using (con = new SqlConnection(conString2))
        {
            con.Open();
            // Do Operations
        }
        scope.Complete();
    }
}

Here the outermost transaction is called as rootscope and here even if the inner transaction (OtherTransaction above) gets completed by calling scope.Complete(), if the rootscope complete could not be called due to various reasons, then the complete transaction would be rolled back including inner transactions.

Note: You might get one of the following exception while executing distributed trsanctions

  1. MSDTC on server is unavailable
  2. Network access for Distributed Transaction Manager (MSDTC) has been disabled.

 

Both the error are due to the same reason, first one occurs when you have the database and the application the same server while 2 if on the other server. For same server, go to run-> cmd-> services.msc. Run the service named Distributed Transaction Coordinator and make the startup type automatic so that it gets started again in case of system restart. For 2, follow the link to cofigure MSDTC.

TransactionScope provides various TransactionScopeOptions which defines transactions behavior for the scope. Lets see an example

using (TransactionScope scope = new TransactionScope())
{
    // Do Operation
    using (TransactionScope scope1 = new TransactionScope(TransactionScopeOption.Required))
    {
        // Do Operation
        scope1.Complete();
    }
    using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        // Do Operation
        scope2.Complete();
    }
    using (TransactionScope scope3 = new TransactionScope(TransactionScopeOption.Suppress))
    {
        // Do Operation
        scope3.Complete();
    }

    scope.Complete();
}

Here we created three transactions under the parent transaction with different TransactionScopeOptions. By default the scope is required, which applies to parent transaction here. It is a rootscope which creates a new transaction, and mark it as an ambient transaction. scope1 is also created with required and as we have already an ambient transaction (scope) so it joins the parent transaction. scope2 got created with option as RequiresNew which means it is a new transaction which is independently works with ambient transaction. scope3 got created with suppress option, which means it doesn’t take part in any ambient transactions. It gets executed regardless whether ambient transaction executes successfully or not. All the ambient transactions gets committed once the parent (global) scope completes.

Hope you enjoyed this post and will be using transaction in your future requirements.

Cheers,
Brij

Span: A new upcoming feature of C#

With the ground-up changes in ASP.NET with ASP.NET Core which is still going on, it appears that now it is turn of C# language and the run-time. I am sure the ground work must have been going on from last couple of years as these changes required massive ground up changes but I am hoping there are lot more changes will take place in future. After using the power of Span<T> and Memory<T> in ASP.NET Core 2.1, which is claimed to be 70-80% faster than ASP.NET Core 1.X, it is planned to release for all of us. In this post, we will be discussing the new type Span<T>. Before jumping directly into Span<T>, let’s have a quick overview current types.

Every object in C# can be categorized in two type: ValueType and Reference Type. We know Value Type instances gets created on stack and only available in the current scope while reference gets created on managed heap which is taken care by Garbage Collector (GC). Garbage collection is expensive process so if we can minimize the reference type object creation and use more Value Type objects then it could be a huge performance benefit. I am not saying that GC is not properly optimized or similar but no GC is always better that any performance optimized GC.  Let’s understand how Span can help in few scenarios.

Note – Currently this feature is available in prerelease state so some changes in final release are expected. To use this this feature, we need we need Visual Studio 2017 15.5+ version and need to install nuget package – System.Memory (Check the include prerelease checkbox while searching it). You can have a look here if getting an error.

What is Span<T>

Span<T> is a ValueType which allows us write low level code in safe and efficient way without any GC overhead. It’s as efficient as working with unmanaged pointers with the benefits of C#. Span<T> represents a contiguous region of arbitrary memory which could be unmanaged memory, memory allocated on stack and arrays or strings.

Let’s understand it with the help of a string.

Here we can see that when we use Substring method on a string, a new copy gets created on the heap. But, we may not want a new copy as we just read that particular part and even sometimes we may need to update the original string itself. Let’s see how does Span<T> work here

So here we can see that we got a ReadOnlySpan from the string and then used Slice (similar to Substring) method of span to get a specific part of the string but here both the variables refer to same memory location. As span is a struct, lastName doesn’t cost any GC overhead. The two parameters of the Slice method are, starting index and length of the sliced part. Let’s see the complete example

Span<Char> name = "Brij Mishra".ToCharArray().AsSpan();

Span<char> lastName = name.Slice(5,4);

lastName[3] = 'k';

Console.WriteLine(lastName.ToString()); // Prints -> Miskra
Console.WriteLine(name.ToString()); // Prints -> Brij Miskra

lastName[5] = 'k'; // Throws Exception -> System.IndexOutOfRangeException'

Here we can see that change in one character using lastName reflects in both the variables. In the last line, when we try to access the fifth character via lastName, it throws IndexOutofRangeException even we know that we have character at this location. But since lastName was created with only four characters, we cannot access it.

Span vs ReadOnlySpan

As the name suggests Span<T> allows us update the values but many a times, we use the sub-string only for readonly purposes. Say we have a method where we need to pass the part of the string which is just needed for reading purposes, it is safer to pass ReadOnlySpan to save from any accidental update because it will affect all the places inside the program. The current version of the package, returns the ReadOnlySpan while getting the span out of string. So if you are sure that we need the span for read only purposes then we should use ReadOnlySpan. Trying to make any changes in ReadOnlySpan will be an compile time error.

Usages

If you are working with payloads where you create and manipulate strings a lot, it can be quite useful. Similarly, parsing needs usage Substring where it can be quite useful. Other usages are not so common like working with buffers and doing multiple transformations like encoding/decoding, parsing, escaping etc. Working with network buffers can be other quite useful scenario.

Limitations

Span<T> is designed to  stay in the stack onlu which is a limiting factor as well. Few key limitations are

  • We can’t box/unbox because it can’t stay on the heap
  • We can’t have it as fields in classes or even in non-ref structs
  • Cannot be used in lambda method because it might turn into field.
  • Due to stack only field, cannot be use in async methods or iterators

Even having quite many limitations, it can be really helpful where you have big structs, file I/O , Network I/O, string manipulations, working with buffers, synchronous methods.

Hope you have enjoyed the post.

Cheers
Brij

How to use the new ValueTuples : A C# 7.0 feature

Tuples are one of the awesome features of C# which was initially introduced with .NET 4.0. Although it is less used but it become very handy when we need to return multiple values from a function. We have another option to use out operator but it is not recommended due to various reasons. I am not going to discuss it in this post. Tuple is a static class under namespace System which implements a Factory pattern to create the instances of Tuples. It has a Create method with eight overloads which allows us to have 8 elements in a Tuple. Also, we can have nested tuples as well.

There were few issues with System.Tuple. It is a reference type so even if you are returning few values type elements , the instance gets created on heap, means adding pressure on Garbage Collector. It doesn’t allow to provide a name to the elements, instead we have to refer it as item1, item2.. etc. Also, the way we used to create Tuple is also quite verbose.

Tuple in C# 7.0

C# 7.0 introduces System.ValueTuple as a new language feature, which resolves the problems mentioned above and provides few more additional features. And Yes, it has the power of Value Type so it removes the GC overhead of the old tuple.

Note: ValueTuple is available as indepedent nuget package. You can install it from here.

Lets see few examples of new Value Tuples,

Tuple Literals

Tuple literal is a comma separated list of literal (of various types), surrounded by parenthesis.

static void Main(string[] args)
{
    // Tuple Literals
    var tpl = (1, 2);
    var author = ("Brij", 32, "https://codewala.net/");
}

public (string, int, string) Author { get; set; } = ("Brij", 32, "https://codewala.net/");

Here we can see that creating Tuple is now a simple assignment operation. Also we can have different types in a Tuple which helps in combining various set of information in a tuple based on the need.

Using Tuples as Return Type

We can use value tuple as return type and the syntax looks so simple as


var author = GetAuthor();

Console.WriteLine($"Author Details: Name: {author.Item1}, Age: {author.Item2}, BlogURL : {author.Item3 ?? "URL not available" } ");

private static (string, int, string) GetAuthor()
{
    string name = "Amit Kumar";
    int age = 33;
    return (name, age, null);
}

Naming the Tuple Elements:
Yes, we can name the tuple elements and this also provides the intellisense support. This is one of the best improvements. We can write the above code as

var author = GetAuthor();
WriteLine($"Author Details: Name: {author.name}, Age: {author.age}, BlogURL : {author.url ?? "URL not available" } ");

private static (string name, int age, string url) GetAuthor()
{
    string name = "Amit Kumar";
    int age = 33;
    return (name, age, null);
}

We can give names in tuple literal as well

var author = (name: "Brij", age: 32, url: "https://codewala.net/");      
Console.WriteLine($"Author Details: Name: {author.name}, Age: {author.age}, BlogURL : {author.url ?? "URL not available" } ");
// Or we can also write as
(string name, int age, string url) author = ("Brij", 32, "https://codewala.net/");

Let’s move to another exciting feature

Value Tuple Deconstruction

Value tuple allows us deconstruct the tuple and access the elements as a local variable. We need to assign a tuple to variable surrounded by parenthesis.  Broadly, it can be done in three ways

  • Providing the types of each element in parenthesis.
  • Using var keyword outside the parenthesis (it is applied to each variable).
  • Or using existing variables

Lets see the examples


// First Option - Providing the type of each element. var is also allowed.
(string authorname, int age, var blog) = GetAuthor();
Console.WriteLine($"Author Details: Name: {authorname}, Age: {age}, BlogURL : {blog ?? "URL not available" } ");

// Second Option - Using var outside of the parenthesis
var (authorname, age, blog) = GetAuthor();
Console.WriteLine($"Author Details: Name: {authorname}, Age: {age}, BlogURL : {blog ?? "URL not available" } ");

// Third option - Using existing variables
string authorname = "Brij";
int age = 32;
string blog = "https://codewala.net/";

(authorname, age, blog) = GetAuthor();
Console.WriteLine($"Author Details: Name: {authorname}, Age: {age}, BlogURL : {blog ?? "URL not available" } ");			

Now it may happen that you are not sure about all the elements or want to discard few , you can use underscore (_) as

var (authorname, age, _) = GetAuthor();
Console.WriteLine($"Author Details: Name: {authorname}, Age: {age}");

Last thing, as we have now System.Tuple and System.ValueTuple both, ValueTuple provide a nice extension method as ToTuple() to convert it to System.Tuple.

C# 7.1 Enhancements: 

There are a small enhancement in C# 7.1 which can save few keystrokes as now elements names are inferred from the variables. Let’s see the example

// Earlier
string name = "Brij";
int age = 32;
string blog = "https://codewala.net/";
var author = (name: name, age: age, blog: blog);

// With C# 7.1 
string name = "Brij";
int age = 32;
string blog = "https://codewala.net/";
var author = (name, age, blog); // Element names would be - name, age, blog

Hope you have enjoyed this post and will be able to use in your day to day coding.

Cheers,
Brij

Use the awesomeness of Pattern Matching with C# 7.0

Pattern Matching is a new feature which was introduced with C# 7.0 which allows us to write cleaner and concise code in many different scenarios. This feature can be said as an extension of is and as operators that we already have in C#. I wrote a post on it earlier, you can take a look here. This feature can be broadly devivded in two sections

  1. Using Is Expression
  2. Using Pattern Matching in Switch Statements

Using Is Expression:

Prior to C# 7.0, Is operator was used to check the type of a variable and based on the type, it returns true or false but with C# 7.0, Is Expression provides following three types of pattern matching

  1. Const Pattern
  2. Type Pattern
  3. Var Pattern

Let’s discuss each with examples

Const Pattern: It allows us to check an object with any value. Let’s see an example

static void IsConstExpression()
{
    Object obj = 2;
    string name = "Brij";

    // null check
    if (obj is null)
        Console.WriteLine("Obj is null");

    // Constant value check
    if(obj is 2)
        Console.WriteLine("Obj has value 2");

    // String value check
    if(name is "Brij")
        Console.WriteLine("name has value \"Brij\"");
}

Above, we can see that we can check to any value including null.

Type Pattern: It allows us to confirm the type of the object and also assigns the value to a new variable of the given type. Prior to C# 7.0, we also had the similar feature but here we can assign to the new variable as mentioned. Lets see the example

static void IsTypeExpression()
{
    Object obj = 2;

    var objPerson = new Person() { FirstName = "Brij", LastName="Mishra" };
    var objNewPerson = new Employee() { FirstName = "Anvit", LastName = "Mishra", Company ="ABC Ltd" };

    if (obj is int i)
        Console.WriteLine($" Variable i has the value {i}");

    if (objPerson is Person person)
        Console.WriteLine($" p is of type {person.GetType().Name} and first name is {person.FirstName}");

    if (objNewPerson is Employee newPerson)
        Console.WriteLine($" p is of type {newPerson.GetType().Name} and first name is {newPerson.Company}");

    if (objNewPerson is Person objPer)
        Console.WriteLine($" p is of type {objPer.GetType().Name} and first name is {objPer.FirstName}");

}

Lets see the output

 

Here Employee inherits from Person. So in the last statement, we have the actual object of Employee but it assigned to a variable of base type.

Var Pattern: This is special case pattern where we check the type as var. This has one difference with the type pattern as it returns true even if it is null. Let’s see example

static void IsVarExpression()
{
    Object obj = new Person() { FirstName = "Brij", LastName = "Mishra" };

    if (obj is var p)
    {
        Console.WriteLine($"Var Pattern : P is of type {p?.GetType().Name}.");
    }

    obj = null;

    if (obj is var per)
    {
        Console.WriteLine($"Var Pattern : P is of type {per?.GetType().Name}.");
    }
}

The output will be as

Here we can see that the second check is also true but since it is null, nothing it displayed where we wrote the type name. Now lets move to switch statements.

Pattern Matching in Switch Statements:

The patterns that we discussed in previous section, can be leveraged in switch statements as well. This becomes very handy when the number of testing conditions grows and using Is pattern becomes tough to maintain.

Earlier switch statement was only supporting constant pattern with limited value types and strings but now we can use Type and var patterns as well. Let’s see the example

switch(p)
{
    case Manager objM:
        Console.WriteLine("p is of Manager type");
        break;
    case Employee objE:
        Console.WriteLine("p is of Employee type");
        break;
    case Person objP:
        Console.WriteLine("p is of Person type");
        break;
    case null:
        Console.WriteLine("p is null");
        break;
}

Here Person is the base class and with the hierarchy Person->Employee->Manager. Based on the type of p case statement gets executed and in case of null, last one gets executed. Here, the key is the most derived type should be first statement. Compiler also gives a warning if the order is not correct. C# 6.0 also provides us capability to use When clause in switch case. Let’s see the example

switch(p)
{
    case Employee objE when objE.Grade == 5:
        Console.WriteLine($"{objE.FirstName} is Manager");
        break;
    case Employee objE when objE.Grade == 5 && objE.Rating >= 3:
        Console.WriteLine($"{objE.FirstName} is Manager and eligible for additional bonus");
        break;
    case var objVar:
        Console.WriteLine("P is not a Employee and is of Type {objVar?.GetType().Name}   ");
        break;
}

Here we can see we can add additional filters in case statements which can be very useful in many scenarios. It also allows to add more that one filter and have various kind of combinations. I have used the var pattern as well in last case statement.

Hope you have enjoyed the post and will be able to use this feature in your day to day work.

Cheers,
Brij

How to use Null Conditional operators

Null values are very special in any language, specifically in C#. Every .NET developer must have pulled his/her hair at some point or other while dealing with it. C# is getting mature by adding more capabilities to handle the null values so that we don’t need to write long repetitive code to handle it. This operator was introduced with C# 6.0 sometimes also referred as safe navigation operator, and can be panacea for the most common NullReferenceException. There are few related topics like Null Coalescing operator, Nullable types, which I will advise to take a quick look before proceeding.

What is Null Conditional Operator?

This is a new operator introduced with C# 6.0, helps in performing null check while accessing its members. It provides following two syntax

  1. First operator: ?.   (Also called elvis operator)
  2. Second operator: ?[

Let’s see it with examples

First Null Conditional Operator (?.):

This operator allows us to access the members or elements of the provided instance only when it is not null. So before moving further, lets create few classes for the example

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }

    public List <Address> Addresses { get; set;}

    public Person Spouse {get; set;}
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }

    public string City { get; set; }

    public string State { get; set; }

    public string Zip { get; set; }
}

If you have to access properties of the person, the usual way of doing it

if(p != null)
{
    string name = p.FirstName;
    int age = p.Age;
}

Now lets see using the ?. operator

string name = p?.FirstName;
int? age = p?.Age;

Here we dont need to have a null check as it is taken care by the null conditional operator. name is assigned to null if either object p is null or FirstName is null. While for age, I had to change the age variable as Nullable type because for value types, this operator returns a nullable type which is easily understandable as it would have no value (or null) if p is null.

Now if want to access the properties of Spouse then normally code would be as

if(p != null && p.Spouse != null)
{
    string name = p.Spouse.FirstName;
    int age = p.Spouse.Age;
}

which can be written as

string name = p?.Spouse?.FirstName;
int? Age = p?.Spouse?.Age;

Here, we avoided two null check and code looks much cleaner and concise. This operators becomes more helpful for the descending types. You must have written similar code like below numerous times while handling a service response

if (response != null && response.Results != null && response.Results.Status == Status.Success)
{
    // Handle response
}

this can be as

if (response?.Results?.Status == Status.Success)
{
        // Handle response
}

It looks super clean now. It could be more granular based on the scenario. Now let’s see another operator.

Second Null Conditional Operator (?[): This operator allows you to have a check over index operator. Let’s see the example.
Here I want to see the city of the second address of the person so normally, we will write it as

if(p!=null && p.Addresses != null && p.Addresses.Count > 1)
{
    string city = p.Addresses[1].City;
}

This we can write now as

string city = p?.Addresses?[1]?.City;

Now you can assume if I have read the same for spouse then how consize code would be.

Other Usages:
It can be used while calling method of instance like

p?.ToString();

We can use it with delegate and events as well like

myCustomDelegate?.Invoke(args)

// Note : myCustomDelegate?(args) won't work and it will be an compile time error

myCustomEvent?.Invoke(this, args);

I found this feature very useful in our day to day coding as we save lot of repetitive code. Hope you find it useful as well.

Cheers,
Brij

String Interpolation in C# with Examples

String is one of the most used types in C# and it provides many options playing with it. I wrote a post earlier where I discussed about String, StringBuilder and String.Fromat. You might want to have a look here. Today I am going to one of the very nice features that got introduced with C# 6, named String Interpolation.

What is String Interpolation?

String Interpolation is a process of generating the output string from a string literal by replacing the placeholders with the actual values. These placeholders could be just variable names or some expressions. It is like template processing where the variables are replaced with actual values to generate the final output. We already have String.Fromat where the values are replaced based on the indexing of provided parameters but we don’t need that now. Interpolation is very common feature in many new libraries and frameworks like Angular.

We will see multiple examples based on various usage of string interpolation. Lets start with basic one

Example 1:

string name = "Brij";
string topic = "String Interpolation";

// Prior to C# 6
Console.WriteLine(string.Format("Hello {0}. Lets learn {1}",name, topic));

// C# 6 and later
Console.WriteLine($"Hello {name}. Lets learn {topic}");

Here both will give the same output. The second option is much cleaner and readable.  As in the above example, to use it, the string should start with $. Let’s see the syntax of interpolated string

$"<text> {<expression> [,<field-width>] [:<format-string>] } <text> ..."  
  • field-width – It defines the width of the field. If positive then value is right aligned and if negative, it is left aligned. If the value is less than the width of the value, there is no impact in the output.
  • format-string – It can be used to define the format of the value like datetime, currency, number etc.

Note – There should be no space between $ and ” at the start of the string else it will htow an compile time error.
Example 2:

int langversion = 6;
string VSVersion = "Visual Studio 2015";
DateTime releaseDate = new DateTime(2015, 7, 20);

Console.WriteLine($"C# {langversion: 0.0} was released with {VSVersion} on {releaseDate: MMM d yyyy}.");

// output

C#  6.0 got released with Visual Studio 2015 on  Jul 20 2015.

If we have any special characters that could provide different meaning to literal then it should be escaped like “, \ etc . If we want a curly braces ({ or }) in the string then it should be written twice as {{ or }}. To use few language elements like colon (:) in expression, it should be delimited by parenthesis as well in expression.

Example 3:

Console.WriteLine($"We can use special meaning characters like \", \\ by escaping it in literal text.");
Console.WriteLine($"We can use {{curly braces}} by using it twice.");
Console.WriteLine($"To use it in expression it should be delimited by paranthesis"
+$" like  2*2 = 4 is {(2*2 == 4? "Correct" : "Incorrect")}");

// Output
We can use special meaning characters like ", \ by escaping it in literal text.
We can use {curly braces} by using it twice.
To use it in expression it should be delimited by paranthesis like  2*2 = 4 is Correct

In the above example, we have seen that how to use special characters in string literals and in expression. Let’s see one more example

Example 4:

Console.WriteLine($"3 power 4 using Math function { Math.Pow(3, 4)} and using custom power "
$"function { CustomPow(3, 4)}.");

// Output
3 power 4 using Math function 81 and using custom power function 81.

Here we can see that we can use any framework class or even custom function in this expression.

Hope you have enjoyed this feature and will start using it.

Cheers,
Brij

What are Immutable types?

In C#, primarly we have two types of objects: reference type and value type. Value type objects always have default value and created on stack. When we assign value type variable to another variable, a new copy gets created. While reference type objects default to null and created on heap. Multiple variables can point to the same object, it means changing the value using one, will reflect accross variables. There is one more type called Nullable type which is similar to value type with additional capability to have no value if it is unassigned. You can learn more about from one of my previous posts here

A reference type can be categorized in two types : Mutable and Immutable. The plain english meaning is “Can Change” and “Cannot Change” respectively and which is same here as well.

It means an Immutable type object cannot be changed after it’s creation/initialization and if one tries to change, a new copy gets created (if allowed) and returned. In other words, it is a reference type but having value type semantics. String is one of the most used immutable types and it is provided by the .NET framework.

Normal class that we create, are mutable type. Let’s see an example

    class Program
    {
        static void Main(string[] args)
        {
            Person objPerson = new Person() { Name = "Brij", Age =32 };
            UpdatePerson(objPerson);
            Console.WriteLine(objPerson.Name);
            Console.ReadKey();
        }

        static void UpdatePerson(Person P)
        {
            P.Name += " Mishra";
        }
    }

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

        public int Age { get; set; }
    }

So in this example the output will be Brij Mishra as the same object got changed. This class can also be modified as where we just provide the getter and the values then can be modified either at constructor or any other method inside the same class.

public class Person
{
    private string _name;
    public string Name { get { return _name; } }

    private int _age;
    public int Age { get { return _age; } }

    public Person(string name, int age)
    {
        this._name = name;
        this._age = age;
    }
}

Now to make it an immutable object, we have two options:

  1. Use Const
  2. Use Readonly

So I can make the class as

   public class Person
    {
        private readonly string _name;
        public string Name { get { return _name; } }

        private readonly int _age;
        public int Age { get { return _age; }  }

        public Person(string name, int age)
        {
            this._name = name;
            this._age = age;
        }
    }

Now once we create an instance of this class, it cannot be updated as all the properties are readonly. Even, we cannot update in another new method in the same class as in the previous example. We can use the Const instead of readonly but in that case, we will loose the ability to assign the value while object creation, instead we will have to provide the value at class definition. One more drawback, as const variable initialized at Class level itself, also called compile time constant so it would be same for all the instances of that type.

Now lets create another class address and have a List of Addresses in the class as

 public class Person
    {
        private List
<Address> _addresses;
        private readonly string _name;
        public string Name { get { return _name; } }

        private readonly int _age;
        public int Age { get { return _age; }  }

        public Person(string name, int age, List
<Address> addresses)
        {
            this._name = name;
            this._age = age;
            _addresses = addresses;
        }
        public List
<Address> Addresses { get { return _addresses; } }
    }

    public class Address
    {
        public string Address1 { get; set; }

        public string Address2 { get; set; }

        public string City { get; set; }

        public string State { get; set; }

        public string Zip { get; set; }
    }

As here the list of address has only get property exposed, it means we cannot replace the whole collection but certainly we can update the items from the list by adding and/or removing an item as

Person objPerson = new Person("Brij", 32, addresses);
objPerson.Addresses.Add(new Address());

Now, to make the Person class Immuatble, we need to change it as readonly collection as

public class Person
{
    private List
<Address> _addresses;
    private readonly string _name;
    public string Name { get { return _name; } }

    private readonly int _age;
    public int Age { get { return _age; }  }

    public Person(string name, int age, List
<Address> addresses)
    {
        this._name = name;
        this._age = age;
        _addresses = addresses;
    }

    public ReadOnlyCollection
<Address> Addresses { get { return _addresses.AsReadOnly(); } }
}

Now we wont be able to add or remove items from list. Still we have here one gap and using we can update any existing address object as Address is not a immutable type.

To make it immutable we will require to make all the properties readonly or const.

So to make an object immuatble, all the internal type used, should also be immutable and all the collection should be readonly.

C# 6 added a feature that says if we have a auto property with only a getter then it can be only initialized in constructor. Behaind the scene, it uses private readonly property as

public class Person
{
    public string Name { get; }

    public int Age { get; }
}

Here if we try to update the properties other than the constructor, it will throw an error stating that it is readonly.

Hope you all have enjoyed the post.

Cheers
Brij

Learning checked and unchecked context

Today, I am going to discuss about one of the rarely used but very useful keywords of C# that are called checked and unchecked context. I learnt this few days back.  These keywords can be used at certain scenarios and can save you from hazardous situations. This would be more useful when you are playing with lots of data and doing lots of operations over it.

So let’s start with a quiz. Just predict the result of the following code snippet

   int value = 5000000;
   int multiplier = 2500;
   int result = value * multiplier;
   Console.WriteLine(result);

What would be the result?
12500000000?   No

It would be -384901888. But how?

Because if you check the max value of int. It is 2147483647. Now you can see that the result of multiplication is higher than this max value. So you can think that the value displayed is min value of int. Which is certainly not desirable.

And even you would not get any overflow exception. So be cautious, while selecting the data types of variable whether it is a normal or temporary variable.

By default, Arithmetic overflow and underflow exception is turned off. You can turn it in on assembly level. For this, you can go to

Project->Properties->build tab-> advanced button. So you’ll get the following screen.

Here you can check the checkbox for arithmetic overflow/underflow and now if you run the code, you will get the OverflowException.

But this got enabled at assembly level and if you want to to have at some code snippet level then first uncheck the above marked checkbox and second you need to use the checked and unchecked keyword to have this feature.

So checked and unchecked keywords are provided for these scenarios. If you want to get exception if some values overflows or underflows.

  
   int value = 5000000;
   int multiplier = 2500;
   int result = 0;
   checked
   {
   	result = value * multiplier;
   }

So if you run the above you’ll get the overflow exception again. What actually checked does, whenever a value is assigned to primitive variable, it the checks with the variable’s max value if the value is greater/lower than the max/min value, it throws overflow/underflow exception.

The above code  that is in checked block, can also be written as

int result = checked((int)(value * multiplier));

One need to be cautious while writing checked/unchecked keyword. This code would not throw any exception.

unchecked keyword also can be used if you don’t want to have a check for overflow/underflow. the code can be written as

            int value = 5000000;
            int multiplier = 2500;
            int result = 0;
            unchecked
            {
                result = value * multiplier;
            }
            Console.WriteLine(result);

If you have enabled overflow exception check at assembly level but don’t want it at certain situations then you can use unchecked keyword.

There are few key points, one need to remember-

  • In any case, you cannot rely on user input whether you have some validation or not. So it’s always recommended that you have this check and code for handling the overflow exception. Even if you are getting from some third party services etc, then also I would recommend this check.
  • You cannot rely on the following code, generally it does not throw overflow/underflow exception.
        static void Main(string[] args)
        {
        	checked
            {
            	addition();
            }
            Console.ReadKey();
        }
    
        private static void addition()
        {
        	int value = 5000000;
        	int multiplier = 2500;
        	int result = 0;
        	result = value * multiplier;
        	Console.WriteLine(result);
        }
    

    I mean, one should write code statements in checked block. If you are calling any method from the checked/unchecked block, you cannot sure that it work as desired.

  • These checked/unchecked context works on CLR primitive types only.
  • System.Decimal is c# primitive type but not CLR. So checked/unchecked context has no effect on this.

I hope you all have enjoyed this feature if didn’t learn it earlier.

Who already aware of this feature, please share some more points that can be added here.

Cheers,
Brij

.NET Datetime vs SQL Datetime : Comparison, Issues and Workarounds

Hello All,

Recently, in an application where we were saving the .NET DateTime value in SQL database, we had to compare this DateTime later in the .NET application. We realized that even the same DateTime stamp was not equating once it got fetched from database. I got Once we investigated further we found that the time stamp that we were sending to save in database, was not saving with the complete value and there were some more issues. It looks common requirement where you saving a value in database and later comparing it to add some business logic.  So I am sharing here my findings.

# 1

SQL DateTime type only stores time till milliseconds (3 digits) while in .NET it is stored till ticks. One millisecond is equivalent to 10,000 ticks. It means if you construct the .NET DateTime object from the DateTime of database, then it will never match because it will have all zero after the milliseconds. Lets see an example.
Here I am showing the same .NET DateTime value at application, in database table and again .NET DateTime read from the DB.

.NET DateTime

{6/19/2017 9:24:14 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 21
      Kind: Local
      Millisecond: 777
      Minute: 24
      Month: 6
      Second: 14
      Ticks: 636335042547778146
      TimeOfDay: {21:24:14.7778146}
      Year: 2017

Let’s see how it is saved in database.

SQL DateTime

In database table it looks like as


When we fetch from database and convert it into it returns the following object
{6/19/2017 9:24:14 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 21
      Kind: Unspecified
      Millisecond: 777
      Minute: 24
      Month: 6
      Second: 14
      Ticks: 636335042547770000
      TimeOfDay: {21:24:14.7770000}
      Year: 2017

Here we see the TimeOfDay component in both the object then we find that while in first object we have 7778146 while in second 7770000, it means last 4 digits are chopped off and reset to 0.
So is it safe if we compare till milliseconds only (say by using ToString(“MM/dd/yyyy hh:mm:ss.fff”))?
NO
There are some more mystery to it. Let’s see in second point

# 2

Here, I saved a new record in the database and the .net DateTime as
{6/19/2017 11:49:55 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 23
      Kind: Local
      Millisecond: 731
      Minute: 49
      Month: 6
      Second: 55
      Ticks: 636335129957315136
      TimeOfDay: {23:49:55.7315136}
      Year: 2017

and when we see the record in the table, we see

Oh.. here we see the 730 millisecond while in .NET object it was 731. Let’s fetch the same and check the .net object as

{6/19/2017 11:49:55 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 23
      Kind: Unspecified
      Millisecond: 730
      Minute: 49
      Month: 6
      Second: 55
      Ticks: 636335129957300000
      TimeOfDay: {23:49:55.7300000}
      Year: 2017

Here again we see 730 millisecond. It means we are losing one millisecond. It also suggests that comparing the two values till milliseconds would also not work. But why this is happening. Let’s dig it more.

Actually SQL DateTime stores till 1/3 millisecond approximately so the last digit of millisecond would always be

**0
**3
**7
**0

and SQL rounds of the milliseconds passed to it so if you pass
001 turns to 000
002 turns to 003
004 turns to 004
005 turns to 007

009 turns to 010

So can we just chop off milliseconds and compare the DateTime?
NO

It may work most of the time. But there are few chances to fail. Say we have a time as 09.00.00.999 then it will turn to 09.00.01.000 so here second got increased by 1. Even minute/hour can be changed if similar situation occur. So here we just have the option to round off the time based on the above logic and then compare.

Do we have any other option?
Yes

DateTime2

To overcome this, there is a new SQL data type datetime2 was introduced in SQL server 2008 which got the ability to save the millisecond till 7th precision. It is like an extension of DateTime which saves the time more accurately. Lets have a look on that

So we see here that the time is saved as 2017-06-19 23:49:55.7353342 while the same was saved in DateTime (type) as 2017-06-19 23:49:55.737 (rounded off). If we now fetch the same and assign the .NET DateTime object we get the exact date time and equality works as expected.

Note – There is one more significant update in datetime2. In DateTime if we want to same a default minimum DateTime then it was 1753 but in DateTime it could be 0001.

Conclusion

In this post, we discussed the behavior of SQL DateTime object, its issues and possible workarounds. Then we saw that the how the issues got resolved in datetime2 which was introduced in SQL server 2008. Obviously, it takes more space in database as it saves the time more granular level. I have rarely seen that DateTime values are stored in datetime2 format, mostly in DateTime at least in legacy application. And many of us don’t know the exact difference or may face the issues that we discussed. If we are working on some legacy application then we may not able to change the SQL data type, in that scenario, putting the round off logic could work.

Hope you have enjoyed the post. Do share your valuable feedback.

Happy Coding,
Brij