Monday, April 2, 2018

DateTime and TimeSpan

DateTime and TimeSpan are actually the structs under the hood. DateTime is used to point the specific time and timespan is used for the duration. Both are immutable (which can’t be change) means that if we initialize the DateTime or TimeSpan variable then we can’t change its value if we need to increment the value or adding days or time then we need to create another variable.

DateTime 

As we already discussed intellisense is a very beautiful tool in the Visual Studio through we can learn programming. We have don’t any need to know which parameter was, what value we need to place here but Intellisense automatically guides us how to insert the value here.

Look how intellisense guides us how to insert the data in datetime object.



 static void Main(string[] args)  
 {  
   DateTime dateTime = new DateTime(2018, 5, 12, 23, 58, 59);  

   // it returns the complete information of date and time  
   DateTime dateTime1 = DateTime.Now;
   Console.WriteLine(dateTime1);      // 4/2/2018 6:49:07 PM    

   // it just returns the information of date  
   DateTime dateTime2 = DateTime.Today;  
   Console.WriteLine(dateTime2);      // 4/2/2018 12:00:00 AM    

   // it returns the date of today  
   DateTime dateTime3 = DateTime.Today.Date;  
   Console.WriteLine(dateTime3);      // 4/2/2018 12:00:00 AM    

   DateTime dateTime4 = DateTime.Now.Date;  
   Console.WriteLine(dateTime4);      // 4/2/2018 12:00:00 AM    

   // But if we try to get the hour then  
   int h1 = DateTime.Today.Hour;  
   Console.WriteLine(h1);         // 0    

   // it is returning 0 because program can't justify the exact value  
   // of hours, today.  
   // Here program can understand the number of hour because of 'Now'  
   int h2 = DateTime.Now.Hour;  
   Console.WriteLine(h2);         // 19    

   bool leapYear = DateTime.IsLeapYear(dateTime.Year);  
   Console.WriteLine("This Year is Leap Year {0}", leapYear);    

   // To add the days in dateTime variable  
   DateTime dateTime5 = dateTime1.AddDays(2);  
   Console.WriteLine(dateTime5);    

   int days = DateTime.DaysInMonth(dateTime1.Year, dateTime1.Month);  
   Console.WriteLine("Total days in month: {0}", days);    // 30    

   // To find out the day of the week  
   DayOfWeek day = DateTime.Now.DayOfWeek;  
   Console.WriteLine(day);    

   Console.ReadLine();  
 }  

This is how datetime works. In short, datetime is used for pointing the data and time. We get the date time information from DateTime object.
We don’t any need to add .ToString() with all of the objects to print them on the console. Because we’re passing the variable into Console.WriteLine() and it (.ToString()) is by default here.


To print tomorrow and yesterday day,
 static void Main(string[] args)  
 {  
   DateTime dateTime = DateTime.Now;  

   // Tomorrow  
   Console.WriteLine(dateTime.AddDays(1).DayOfWeek);    // Tuesday  

   // Yesterday  
   Console.WriteLine(dateTime.AddDays(-1).DayOfWeek);   // Sunday  

   Console.ReadLine();  
 }  

Custom Date And Time Format Strings

As we need to print the date and time on the console in specific format so we need to manually attach the .ToString() and custom format specifier with it.
As we can see how intellisense helps us to specify the format here and telling us the results as well. All this is the beauty of Visual Studio Intellisense feature and Resharper. Now we need to just specify the letter or letters in .ToString()
 static void Main(string[] args)  
 {  
   DateTime thisDate = new DateTime(2018, 8, 17);  
   Console.WriteLine(thisDate.ToString("d"));  
   Console.ReadLine();  
 }  
To print all the date patterns on the screen.
 static void Main(string[] args)  
 {  
   if (DateTimeFormatInfo.CurrentInfo != null)  
     foreach (var pattern in DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns('d'))  
     {  
       Console.WriteLine("{0}", pattern);  
     }  
   Console.ReadLine();  
 }  

TimeSpan

Timespan represents the duration. And we can add this exact time of duration in our datetime object.
 static void Main(string[] args)  
 {  
   DateTime today = DateTime.Today;  
   TimeSpan day = new TimeSpan(1, 2, 26, 41);  
   DateTime newDateTime = today.Add(day);  
   Console.WriteLine(newDateTime);  
   Console.ReadLine();  
 }  
This is how it works.

Note:

Do you notice when we’re working with DateTime then to add days, hours, minutes we were using datetime.AddDays, datetime.AddHours But now we’re working with Timespan we just use the .Add()
 today.Add(day);  

DateTime and TimeSpan are Immutable

As we already know that DateTime and TimeSpan both are immutable. When we initialize their values then we can’t change them later on. Look this piece of code doesn’t work as you expect.
 static void Main(string[] args)  
 {  
   DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);  
   TimeSpan t = new TimeSpan(1, 0, 0, 0);  
   date.Add(t);  
   Console.WriteLine("A day after the day: " + date);  
   Console.ReadLine();  
 }  
Here ‘date’ value doesn’t change actually. And another thing is Add() returns a new DateTime object which we need to catch. So to resolve above problem, we’ve 2 solutions.
 static void Main(string[] args)  
 {  
   DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);  
   TimeSpan t = new TimeSpan(1, 0, 0, 0);  

   // 1st solution  
   date = date.Add(t);  
   Console.WriteLine("A day after the day: " + date);  

   // 2nd solution  
   Console.WriteLine("A day after the day: " + date.Add(t));  

   Console.ReadLine();  
 }  

Variable Scope, Overflowing Checked and Unchecked Keywod

Scope

Scope is actually all about accessibility of the variable. The point where we can access it, we can use it, we can read or write the variable. These are the things are actually the scope of the variable. If we define the variable at global level then we can access it in functions as well. Similarly the scope of a procedure and function is defined by the place where we can call that method and where you’re allowed to call that method. This defines the scope of variables and functions.
Here we’ve different levels where we define the variable.

Block Level

If we define the variable at block level then it can be accessible within the block. We can’t access it and use it outside of the block.

Procedure/Function

Same as above if we define the variable in functions then its scope is within the ending the curly braces of function.

Class

If we define the property at class level then its scope is dependent upon the access modifier through which we define the class itself, its properties and methods.

Project

Like if you’ve import the assembly into your project then the properties methods which are public or static can be accessible in that specific object.
We’ll define the access modifiers later on in this series.

Overflowing

Actually we already know that every container has its own limit which it can hold the value, each data type has minimum value and maximum value as well that we can store into it but if we cross the boundary and put the value more than the value that it should have then normally it shows us the minimum least value that it can hold but it don’t throw the exception.
And if we decrement the value more the last digit this datatype can have then we’ll see the maximum last digit it have.
But now this kind of implementation is not so much good. The program should throw the exception in such kind of scenarios. Then we’ve 2 techniques for this purpose.
  • ·        Turn on the compiler settings
  • ·        Use the checked and unchecked keyword
Let’s discuss them one by one

Compiler Settings

  • ·        Paste this code in Visual Studio
 static void Main(string[] args)  
 {  
   int a = int.MaxValue;  
   Console.WriteLine("Max Value of int is {0}", a);  
   int b = ++a;  
   Console.WriteLine("Max Value of int after Increment {0}", b);  
   Console.ReadLine();  
 }  
  • ·        Now right click on the project and select properties
  • ·        In Build Tab Click on Advanced Button and mark the checkbox
  • ·        Now run the application. And you’ll see the exception.

Checked Keyword

  • ·        Now uncheck the checkbox and just paste the code into the checked block.

 static void Main(string[] args)  
 {  
   checked  
   {  
     int a = int.MaxValue;  
     Console.WriteLine("Max Value of int is {0}", a);  
     int b = ++a;  
     Console.WriteLine("Max Value of int after Increment {0}", b);  
   }  
   Console.ReadLine();  
 }  
  • ·        Now run the application and now our program is throwing exception.
So this is how we can use these kind of things in our program to know that something is wrong happening there.

Unchecked Keyword

Unchecked keyword actually allow us and prevent us from the exceptions when the developer make sure about the possible results then he applies unchecked block on the code.
Look when we’re using const keyword with the datatype then it doesn’t matter whether you’re changing this value or not but even you can’t assign the value to any container by incrementing this constant value.

In such kind of scenarios, we need to use unchecked keyword here.


Boxing, Unboxing And Casting

Boxing is the concept of converting value type to reference type and unboxing is to convert reference type to value type. Boxing is implicit but we need to explicitly unbox the variables with the help of casting concept.

 double x = 123.45d;  
 object obj = x;                       // boxing  
 double y = (double)obj;               // unboxing  
But now you might be thinking about actual why we need to use boxing and unboxing and why we need to use like this kind of programming.

The answer of this question is suppose you’re using a library which has a method like,

 public static object CalculateSimpleInterest(ref object principalAmount)  
 {  
      return (2 * 5 * (double)principalAmount) / 100;  
 }  
And now you want to use it then the value whatever you’ve you need to box it firstly and then unbox the results. And we already know that boxing is implicit but unboxing is explicit.

 double x = 125600.876d;  
 object obj = x;                                                       // boxing  
 object SimpleInterest = (double)CalculateSimpleInterest(ref obj);     // unboxing  
But remember that boxing and unboxing both has its own drawbacks, they have performance issues. So we just need to perform boxing and unboxing only when we really need them otherwise we should avoid from them.

Casting

Casting is actually all about to change the type of the variable and convert it into some other type which we want. Here we’ve 2 types of casting.
  • ·        Implicit type casting
  • ·        Explicit type casting
As we know that a small bucket water can be poured into the bigger bucket. Similarly, we know different types of numerical and fractional buckets. So if we try to place the value of smaller numerical bucket (int) into the bigger numerical bucket then C# compiler automatically do it for us just by assigning the values implicitly. But if we’re putting the value of the bigger container into the smaller container then we need to make sure our own and tell the compiler that it is ok, the bigger container has small value which can be put into the smaller container otherwise the value will be overflow from the small container and data might be lost.
But if long container has a bigger value which can’t assign into the int then C# compiler will generate the error because this type of problem might loss the data during the conversion and it is difficult to catch such kind of error.

Similarly if we want to convert the fractional type value into the numerical then we need to explicitly tell the compiler to allow him for conversion and in result this conversion will lost the fractional value of floating number.
Another noticeable thing is if we cast the fractional number into numerical one then it is ok. But if we cast the fractional number into ‘object’ and then try to cast this dynamic object into numerical container then we’ll see the error because we can’t directly cast the fractional reference type value into numerical type.

 double num = 2.12454d;  
 int num1 = (int) num;                          // it is ok  
But if we try to do it,

 double num = 2.12454d;  
 object obj = num;  
 int num1 = (int) obj;                          // runtime exception  
To resolve this kind of issue,

 double num = 2.12454d;  
 object obj = num;  
 int num1 = (int)(double) obj;  
First we’ve to explicitly unbox ‘obj’ into double and then cast it into integer. This is how it works.

Sunday, April 1, 2018

Value Type And Reference Type

Before we get started between the difference of value type variables and reference type variables, we need to understand the concept of stack and heap. So let’s get started with stack and heap.

Stack VS Heap

We’re actually working in the machine environment and we already know that the way we treat with program is different and it executes in different way under the hood. Normally we assign the single value in the container as the value is single so we call such kind of container is static memory which holds only 1 value.

 int x = 123;  
This value stores on the top of the stack.

We already know that these values are actually meaningful for us but computer understands the values in numbers and we know that the ASCII Code of ‘A’ is 65. So let’s suppose,

 char c = ‘A’;  
So computer understands ‘A’ itself as a number 65 under the hood. And as we can see ‘A’ is just a single value, 123 is also a single value. So we call these containers as static containers and these variables are store into the stack (LIFO) and they are not complex.

But the datatypes which holds more than 1 value, these datatypes are complex datatype. We know the architecture of Stack and heap.


In Stack, variables are places one by one on the top of each other in memory. But heap is actually the dynamic memory which we use according to our need.
Let’s discuss the comparison between string and char
As we know that string can be any lengthy but char just holds the single character. So if,

 char c1 = ‘a’;  
 char c2 = ‘b’  
 char c3 = c1 + c2;  
Then we’ll see the error because char can hold just single value (ascii number of single value) and here we’re using the syntax of concatenation of string. But as the string can be any length. So, it works

 string str1 = “a”;  
 string str2 = “b”;  
 string str3 = str1 + str2;  

Here string can hold large values so these string join with each other and here it works.

Why String and Class Are Reference Type?

string, object, arrays, class are actually store into the heap because they are dynamic. Let’s discuss them.

 string name = “Muhammad”;  
Look we’ve already discussed that computer understand the alphabets into the numbers. And here we have 8 letters which have different ascii numbers. So it stores the data into the heap and we’ll just pass the reference of the first letter in stack. See the images below and you’ll get the idea what is happening under the hood.

And here these items are actually characters and they store into the memory into the ascii numbers form.
This is how string works. As program executes into the stack and stack block points to the first character of the string because it has the reference of the first character’s memory reference. And then this first character has the address of the next character reference block which has the value of the 2nd character.
Similarly, in classes we’ve multiple primitive data types and functions. So they are also complex and they store into the heap. But the object’s reference stores into the variable in stack to point to that specific object.
And if we discuss the ‘object’ we know that it is actually the dynamic type so we can store the different kind of values in it. Don’t confuse about collection/list just look what we can do with ‘object’.

     static void Main(string[] args)  
     {  
       List<object> objList = new List<object>();  
       int sum = 0;  
       // Adding Name  
       objList.Add("Muhammad Usama");  
       // Adding Numbers  
       for (int i = 1; i < 10; i++)  
       {  
         objList.Add(i);  
       }  
       // Displaying Numbers  
       foreach (var o in objList)  
       {  
         Console.WriteLine(o);  
       }  
       // Casting  
       for (int i = 1; i < 10; i++)  
       {  
         // We can't apply operations directly on object. We need to cast  
         // them before use.  
         // sum += objList[i] * objList[i];  

         // We can't apply any numerical operation on 'object' directly  
         // We need to cast it then we can apply operation on it.  
         sum += (int) objList[i] * (int) objList[i];  
       }  
       Console.WriteLine(sum);  
       Console.ReadLine();  
     }  
As we can see, we can store different type of primitive values into the ‘object’ because it is dynamic memory. We can allocate anything into the dynamic container. Another noticeable thing is we can’t apply the operations directly on the object container because it can’t be possible to apply the numerical operations on the dynamic memory container until it needs a lots of customization or coding. So we need to cast the ‘object’ container first into a specific type to apply the operations upon it which we can apply on that specific container.

If we’re casting ‘object’ into string then we can concatenate it, if we’re casting it into numerical container then we can apply the numerical operations upon it. So conclusion is, the operations which we want to apply is dependent upon the casting. Here is the output of the above program.

Value Type and Reference Type

The built-in types are also known as value types because variables store the actual data. But reference types just store the reference of that specific object.
Let’s discuss value type and reference type with some other dimension.

 int a = 20;  
 int b = a;  
When we assign the value type to another value type then the new copy of container ‘b’ will be generated. Because ‘a’ has value and now this value is also assigned to another variable ‘b’. But in reference type case,

 Class1 obj = new Class1();  
 Class1 obj1 = obj;  
Here obj has the reference of the object which places into the heap and now this reference is copies into the obj1 as well. Now both variables are pointing to the same memory location. This is how reference type works.

Monday, March 19, 2018

DataTypes And .Net Types (CTS)

As we already know that we make the variable to allocate the memory space in our program to store the values. But in programming languages, we always need to define the type of the variable like (int, float, decimal, short etc.). With the help of these datatypes, computer can understand what kind of container he allocate, how much the size will be of this container and how much the value we can store in this variable, what the operation we can manipulate on this container. These kind of things are actually defined by the data types.
In C#, we’ve many kind of built-in data types. Let’s discuss some basic data types one by one.
Alias
Type Name
.Net Type
byte
System.Byte
struct
sbyte
System.SByte
struct
int
System.Int32
struct
uint
System.UInt32
struct
short
System.Int16
struct
ushort
System.UInt16
struct
long
System.Int64
struct
ulong
System.UInt64
struct
float
System.Single
struct
double
System.Double
struct
char
System.Char
struct
bool
System.Boolean
struct
object
System.Object
Class
string
System.String
Class
decimal
System.Decimal
struct
dateTime
System.DateTime
struct
Look we use these data types which are actually the aliases of these Type Names and the .Net Types of these type names are also given above. Look int is actually an aliase of System.Int32 and Int32 is a struct under the hood. string is an alias of System.String which is a class.

Integer Data Type
Integer data type is commonly used to store the whole numbers. It is commonly used data type. We’ve different kind of datatypes depending upon the size and the values weather the integer is signed (positive or negative) or unsigned (positive only).

Signed Integrals are
Unsigned integrals are
In these documentation articles, examples and notes are important. So read them.

Let’s discuss the ranges of these data types.
Signed Integrals
long: (64 bits, 8 byte) -9223372036854775808 to 9223372036854775807
int:    (32 bits, 4 byte) -2147483648 to 2147483648
short: (16 bits, 2 byte) -32768 to 32768
sbyte: (8 bits, 1 byte) -128 to 127
Unsigned Integrals
ulong: (64 bits, 8 byte) 0 to 18446744073709551615
uint:    (32 bits, 4 byte) 0 to 4294967295
ushort: (16 bits, 2 byte) 0 to 65535
byte: (8 bits, 1 byte) 0 to 255

Fractional Data Types
Fractional Data Types are often used to store the real numbers. Here we also have different types of Fractional Data Types. Fractional data types are important in calculation scenarios which gives us accurate results like in banking applications.
Fractional Data Types, their sizes and ranges are
float: (32 bits, 4 byte) 1.5 × 10−45 to 3.4 × 1038, 7-digit precision
double: (64 bits, 8 byte) 5.0 × 10−324 to 1.7 × 10308, 15-digit precision
decimal: (128 bits, 16 byte)  –7.9 × 10−28 to 7.9 × 1028, with at least 28-digit precision

Suffixes Explaination
Let’s discuss fractional data types with their suffixes. Actually real numbers declared as double by default. And if we don’t specify the suffix then we’ll see error.

We’re seeing the red squiggle line because we’re trying to store the double value into float & decimal data type container and implicit conversion is not allowed here and we’re not watching any red line under double variable statement. But if we use the suffixes to describe the value types explicitly then we can resolve this problem.

String Data Type
Actually most of the beginners confuse between these two things string and String and even most of the expert developers don’t know the difference.
string is actually the alias of String (System.String), each and everything which we can do with the String we can do with string as well. As we can see both keywords String and string has same results. String is a reference type and we know reference type can be null. We can initialize the string as empty string ("") but we have another technique to make the string empty. Both are equivalent to each other but this second approach is better then first one.

 string name = String.Empty;  

Boolean Data Type
it is used to declare the Boolean variables to store the true and false values. And Boolean type can’t cast/convert into any other type but in C++.

Size Of Data Types
Yes we can find out the size of the data type in our program with the help of sizeof() function. This operator shows the size in byte.

 class Program  
 {  
   static void Main(string[] args)  
   {  
     Console.WriteLine(sizeof(int));  
     Console.ReadLine();  
   }  
 }  


.Net Type And CTS
As we already know that declaration of variables in .Net different programming languages like C#, VB, F# has different way. But these programming languages actually use the same base class library this is called Common Type System. So that 1 language program can easily understand the information of different programming language in .Net
Look we’ve 2 different projects in our Solution ‘HelloWorld’ for C# and VBProject for Visual Basic Console Application.