Tuesday, 28 April 2020

C# - Nullable type or ? on variable


Nullable<T> type or  ? on variable

Represents a value type that can be assigned null.
It's a nullable value. Structs, by default, cannot be nullable, they must have a value, so in C# 2.0, the Nullable<T> type was introduced to the .NET Framework.
C# implements the Nullable<T> type with a piece of syntactic sugar, which places a question mark after the type name, thus making the previously non-nullable type, nullable.

Explanation 

   //Cannot Be Null
   DateTime
   DateTime dt = null;   // Error: Cannot convert null to 'System.DateTime'
                         //because it is a  non-nullable value type
   //Can Be Null
   DateTime?             //Nullable < DateTime >               
   DateTime? dt = null;  // no problems



Example 1
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System;

class Sample
{
    // Define the "titleAuthor" table of the Microsoft "pubs" database.
    public struct titleAuthor
    {
        // Author ID; format ###-##-####
        public string au_id;
        // Title ID; format AA####
        public string title_id;
        // Author ORD is nullable.
        public short? au_ord;
        // Royalty Percent is nullable.
        public int? royaltyper;
    }

    public static void Main()
    {
        // Declare and initialize the titleAuthor array.
        titleAuthor[] ta = new titleAuthor[3];
        ta[0].au_id = "712-32-1176";
        ta[0].title_id = "PS3333";
        ta[0].au_ord = 1;
        ta[0].royaltyper = 100;

        ta[1].au_id = "213-46-8915";
        ta[1].title_id = "BU1032";
        ta[1].au_ord = null;
        ta[1].royaltyper = null;

        ta[2].au_id = "672-71-3249";
        ta[2].title_id = "TC7777";
        ta[2].au_ord = null;
        ta[2].royaltyper = 40;

        // Display the values of the titleAuthor array elements, and
        // display a legend.
        Display("Title Authors Table", ta);
        Console.WriteLine("Legend:");
        Console.WriteLine("An Author ORD of -1 means no value is defined.");
        Console.WriteLine("A Royalty % of 0 means no value is defined.");
    }

    // Display the values of the titleAuthor array elements.
    public static void Display(string dspTitle,
                               titleAuthor[] dspAllTitleAuthors)
    {
        Console.WriteLine("*** {0} ***", dspTitle);
        foreach (titleAuthor dspTA in dspAllTitleAuthors)
        {
            Console.WriteLine("Author ID ... {0}", dspTA.au_id);
            Console.WriteLine("Title ID .... {0}", dspTA.title_id);
            Console.WriteLine("Author ORD .. {0}", dspTA.au_ord ?? -1);
            Console.WriteLine("Royalty % ... {0}", dspTA.royaltyper ?? 0);
            Console.WriteLine();
        }
    }
}
// The example displays the following output:
//     *** Title Authors Table ***
//     Author ID ... 712-32-1176
//     Title ID .... PS3333
//     Author ORD .. 1
//     Royalty % ... 100
//    
//     Author ID ... 213-46-8915
//     Title ID .... BU1032
//     Author ORD .. -1
//     Royalty % ... 0
//    
//     Author ID ... 672-71-3249
//     Title ID .... TC7777
//     Author ORD .. -1
//     Royalty % ... 40
//    
//     Legend:
//     An Author ORD of -1 means no value is defined.
//     A Royalty % of 0 means no value is defined.


C# - ?? and ??= operators (Null-Coalescing)

?? and ??= operators

The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.
Available in C# 8.0 and later, the null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

Example 1:
 List<int> numbers = null;
 int? a = null;

 (numbers ??= new List<int>()).Add(5);
 Console.WriteLine(string.Join(" ", numbers));  // output: 5

 numbers.Add(a ??= 0);
 Console.WriteLine(string.Join(" ", numbers));  // output: 5 0
 Console.WriteLine(a);  // output: 0

Example 2:
 double SumNumbers(List<double[]> setsOfNumbers, int indexOfSetToSum)
 {
     return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? double.NaN;
 }

 var sum = SumNumbers(null, 0);
 Console.WriteLine(sum);  // output: NaN

Example 3:
public string Name
{
get => name;
set => name = value ??
throw new ArgumentNullException(nameof(value), "Name cannot be null");
}

Monday, 27 April 2020

C# - Concurrency (Synchronous) vs Parallelism (Asynchronous) vs Thread Or MultiThread


Concurrency (Synchronous) vs Parallelism (Asynchronous) vs Thread Or MultiThread

Concurrency and Parallelism -> Way tasks are executed.
Synchronous and Asynchronous -> Programming model.
Single Threaded and Multi-Threaded -> The environment of task execution.

Concurrency
Consider you are given a task of singing and eating at the same time. At a given instance of time either you would sing or you would eat as in both cases your mouth is involved. So, in order to do this, you would eat for some time and then sing and repeat this until your food is finished or song is over. So, you performed your tasks concurrently.
Concurrency means executing multiple tasks at the same time but not necessarily simultaneously.
Parallelism
Consider you are given two tasks of cooking and speaking to your friend over the phone. You could do these two things simultaneously. You could cook as well as speak over the phone. Now you are doing your tasks parallelly.

How Is Concurrency Related To Parallelism?
Concurrency and Parallelism refer to computer architectures which focus on how our tasks or computations are performed.
        i.            Single core environment, concurrency happens with tasks executing over same time period via context switching i.e at a particular time period, only a single task gets executed.
      ii.            Multi-core environment, concurrency can be achieved via parallelism in which multiple tasks are executed simultaneously.

Threads & Processes
Threads
Threads are a sequence of execution of code which can be executed independently of one another. It is the smallest unit of tasks that can be executed by an OS. A program can be single threaded or multi-threaded.
Process
A process is an instance of a running program. A program can have multiple processes. A process usually starts with a single thread i.e a primary thread but later down the line of execution it can create multiple threads.

Synchronous & Asynchronous
Synchronous
Imagine you were given to write two letters one to your mom and another to your best friend. You cannot at the same time write two letters unless you are a pro ambidextrous.
In a synchronous programming model, tasks are executed one after another. Each task waits for any previous task to complete and then gets executed.
Asynchronous
Imagine you were given to make a sandwich and wash your clothes in a washing machine. You could put your clothes in the washing machine and without waiting for it to be done, you could go and make the sandwich. Here you performed these two tasks asynchronously.
In an asynchronous programming model, when one task gets executed, you could switch to a different task without waiting for the previous to get completed.

What is the role of synchronous and asynchronous programming in concurrency and parallelism?
        i.            Synchronous programming model helps us to achieve concurrency.
      ii.            Asynchronous programming model in a multi-threaded environment is a way to achieve parallelism.



Saturday, 25 April 2020

C# - $ - String Interpolation

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6. String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature. The following example uses both features to produce the same output:

string name = "Mark";
var date = DateTime.Now;
// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.

Console.WriteLine($"|{"Left",-7}|{"Right",7}|");
const int FieldWidthRightAligned = 20;
Console.WriteLine($"{Math.PI,FieldWidthRightAligned} - default formatting of the pi number");
Console.WriteLine($"{Math.PI,FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");
// Expected output is:
// |Left   |  Right|
//     3.14159265358979 - default formatting of the pi number
//                3.142 - display only three decimal digits of the pi number


string MyName = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {MyName}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
// Expected output is:
// He asked, "Is your name Horace?", but didn't wait for a reply :-{
// Horace is 34 years old.


double speedOfLight = 299792.458;
FormattableString message = $"The speed of light is {speedOfLight:N3} km/s.";
System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = message.ToString();
var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCulture);
string messageInInvariantCulture = FormattableString.Invariant(message);
Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");
// Expected output is:
// nl-NL      The speed of light is 299.792,458 km/s.
// en-IN      The speed of light is 2,99,792.458 km/s.
// Invariant  The speed of light is 299,792.458 km/s.