Friday, March 31, 2017

The if keyword

The if keyword


The if keyword plays a vital role of a program logic. You use if and else keywords to design a decision structure so that you can change the path of execution or program flow for a specific condition. 

if-then-else

You evaluate that if a condition is either true or false. The result of evaluation changes the course of a program. 

Among the few decision structures provided by C# we will look at the if and else pattern of writing logic into our code.

Note: The condition must evaluate to either true or false.

In the if construct the condition is evaluated and if it evaluates to a value of true then the statement or a block of statements in the then part will be executed like so

The if keyword

Sample 1

-When you only want to check for truthy
if(condition)
       statement or block


-When you want an alternative if the condition is not truthy
if(condition)
{
     statement or block
}else
{     statement or block
}

-When you want many alternatives if the condition is not truthy
if(condition)
{
       statement or block
}
else if(condition)
{
       statement or block
}
else
{
       statement or block
}


Example 1

int a  = 5;
int b  = 2;

if ((a+b)==7){
     Console.WriteLine("Yes a+b is 7");
}
Console.WriteLine("Hi I will be executed anyway");

Example 2:

What if the condition evaluates to false? You may want to check for something else like so....

Code to check the names before passing the key. Only Alan or Sara can have the key..

string name = Console.ReadLine(); //user types "Alan"

if(name.Equals("Alan"))
{
       Console.WriteLine("The name is Alan. Give him the key.");


}
else if(name.Equals("Sara"))
{
       Console.WriteLine("The name is Sara. Give her the key.");


}
Console.WriteLine("The name does not match Alan or Sara. Don't give the key.");


Example 3:

You can write nested if's and else's within an if or an else block.

int number = 56;

if(number > 100)
{
     Console.WriteLine("The number is greater than 100");
}
else 
{      if(number > 50)
     {
             Console.WriteLine("The number is greater than 50");
     }
     else
     {             Console.WriteLine("The number is less than 50");
     }}





Saturday, February 11, 2017

CSharp Primary Operators

Primary Operators in C#


C# has a rich set on operators. In this post we will discuss primary operators. They are called primary operators because they require only one operand. There are operators that take more two operand called binary operators. The ternary operator requires three operands. We will look at the binary and ternary operator in the next post. 

Operators are symbols written as part of an C# expressions or statements. When applied to the operands they performs a specific function and may transform that operand.


According to MSDN, the primary operators are as follows:



x.y: Used to access a property or a function of the left hand variable

Car c = new Car();

car.Gear = 1; //Access property of c
car.Move(); //Access function of c




f(x): Used to specify the order of operation and also used for type conversion 



Order of expression
3*(2+6)

Type Conversion

float y = 4.5f;            
Console.WriteLine("float to int {0}", (int)y);



a[x] The square brackets are used in three ways

a) To define an array
b) To access an element of an array
c) To decorate classes or members of a class with additional information called metadata

a) Define an array


int[] x = new int[10];


b) To access an element of an array


private static void ArraySample()

{
    int[] myarray = new int[10];
     for (int i = 0; i < 10; i++) {
            myarray[i] = i*5;
      }
     foreach(var element in myarray)
         Console.WriteLine(element);

}


c) To decorate classes with Attributes


using System.Runtime.InteropServices;   

class Program
{
   [DllImport("kernel32.dll")]
    public static extern bool Beep(int frequency, int duration);

    static void Main(string[] args){

             Beep(500, 2000);
     }
}


x++: Increments the variable by one. This is a shortcut for x = x+1;

for (int i = 0; i < 5; i++)
{
  Console.WriteLine(i);
}


x--: Decrements the variable by one. This is a shortcut for x = x-1;

int i=10;
while (i > 0)
{
  Console.WriteLine(i++);
}


new operator: The new operator is used to create a reference type and allocate memory to it. It is also used to create delegate. 

This operator has many forms:

Examples:

1. Cat kitty = new Cat()
2. Cat kitty = new Cat(){ age:2, color: black};
3. new {}: This notation is used to create an anonymous types
4. new T[]: Used to create an array of type T


typeof: The operand expects a Type and it returns the Type object which contains the information for that type. You cannot pass an object reference to the typeof operator as the compiler will report an error. 

Examples:

Console.WriteLine(typeof(int));    //outputs: System.Int32
Console.WriteLine(typeof(string));    //outputs: System.String
Console.WriteLine(typeof(MyType));    //outputs: ConsoleApplication1.MyType
Console.WriteLine(typeof(MyType).BaseType);    //outputs: System.Object

MyType myType = new MyType();
Console.WriteLine(typeof(myType)); //Error CS0118  'myType' is a variable but is used like a type


As you can see that the Type object is returned from the typeof operator. You can use to this information to find its base type, declaring assembly, and much more. We will more more on this when we discuss reflection in C#.


checked: The checked operator checks for overflows on an expression containing integral types. When a variable is assigned a value that it cannot hold the value is wrapped to negative. By default the run-time does not checks for such overflows so you may want to trap the result of such expressions or conversions early on.

Note that the compiler checks for the overflow assignments if the expression only contains constant values. If the expression whose value is to be assigned contains variables then the overflow will go undetected.

In the example below we are assigning the same value to both variable j and k. While the loop for j complete its 5 iterations, the result of the increment becomes invalid after the maximum value of 2147483647 is reached. After that the value wraps to negative.

In the case of variable k, we see that only 2 iterations were successful and the third one caused an exception to occur when the overflow occurs since we placed it inside the checked block.

Examples:



           Console.WriteLine("Min Value of an integer: " + Int32.MinValue);
           Console.WriteLine("Max Value of an integer: "+Int32.MaxValue);

            int j = Int32.MaxValue - 2;

            Console.WriteLine("Working with J");
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(++j);
            }

            Console.WriteLine("Working with K");
            int k = Int32.MaxValue - 2;
            for (int i = 0; i < 5; i++)
            {
                checked
                {
                    Console.WriteLine(++k);
                }
            }


Output:


Min Value of an integer: -2147483648
Max Value of an integer: 2147483647
Working with J
2147483646
2147483647
-2147483648
-2147483647
-2147483646
Working with K
2147483646
2147483647








unchecked: Any integral operation or conversion that caused an overflow is suppressed when used inside the context of unchecked keyword. 

If you assign a constant value, or an expression containing only constants to an integral datatype, the overflow is caught by the compiler. If the expression contains even a single variable (non-constant value) then the overflow goes undetected. This behavior applies for compile time and run-time and is the default behavior. 


Examples:


All constants on the right side causes the compiler to report overflow:
int x = In32.MaxValue + 1; //Error CS0220 The operation overflows at compile time in checked mode

Expression containing non-constants does not causes compiler to report an overflow nor is it reported during run-time. The value of x is printed which is outside of its range.

            int maxValue = Int32.MaxValue;

            int x = maxValue + 1; //Expression containing constants and non-constants

Output

-2147483648



default: The default keyword is used to get the default value in a switch statement.

Example:


            Console.WriteLine("Press 1,2 or 3 to select an menu");
            string pressedKey = Console.ReadKey().Key.ToString();

            switch (pressedKey) {
                case "1": Console.WriteLine(" You pressed 1"); return;
                case "2": Console.WriteLine(" You pressed 2"); return;
                case "3": Console.WriteLine(" You pressed 3"); return;
                default: Console.WriteLine(" You did not press any of the required key"); return;
            }






delegate: The use of delegate is that of a function pointer or callbacks. The declaration of a delegate is like declaring a function prototype or a method signature. 

When we say that a delegate take a function signature it means that the object referenced by a delegate is a function with a specific signature. Any function with such a signature can be referenced by such a delegate. Delegate are mostly used to define events. For now we will just look at an example of a declaring a delegate.


Sample of a delegate whose name is MyDelegate, returns void and takes two integer parameters.

public delegate void MyDelegate(int x, int y);



sizeof: The sizeof keyword is used to determine the size of a type in bytes. 

Example:

            Console.WriteLine("Size of int:"+sizeof(int));
            Console.WriteLine("Size of uint:"+sizeof(uint));
            Console.WriteLine("Size of long:"+sizeof(long));
            Console.WriteLine("Size of ulong:" + sizeof(ulong));
            Console.WriteLine("Size of double:"+sizeof(double));
            Console.WriteLine("Size of char:" + sizeof(char));


Output

Size of int:4
Size of uint:4
Size of long:8
Size of ulong:8
Size of double:8
Size of char:2

 

Saturday, January 28, 2017

CSharp - Read data from a text file

Read data from a text file.

Reading data from a text file in C# is pretty straight forward. The namespace that contains classes that you can use to perform input/output operations is "System.IO". To read data you can use the StreamReader class that provides many methods of reading data. Please refer to MSDN for details on the constructors of StreamReader.

In the example below, I am reading data from a text file called "data.txt". Since StreamReader class implements the IDisposable interface you can explicitly call the Dispose() method once you have finished reading the file or use can use the using{} construct which automatically disposes the StreamReader object.


Sample Code


using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
           static void Main(string[] args){
                ReadTextFile(); 
                Console.Read();
        }

        private static void ReadTextFile()
        {
            try
            {
                using (StreamReader streamReader = new StreamReader("C:\\data.txt"))
                {
                    string dataLine;
                    while ((dataLine = streamReader.ReadLine()) != null)
                    {
                        Console.WriteLine(dataLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: Unable to read the file");
                Console.WriteLine(ex.Message);
            }
        }
    }


1. using (StreamReader streamReader = new StreamReader("C:\\data.txt"))

The above line creates a new instance of StreamReader and puts a handle on the file located on C:\data.txt.


2. string dataLine;
    while ((dataLine = streamReader.ReadLine()) != null)
    {
            Console.WriteLine(dataLine);
    }

A variable dataLine is declared to hold each line read from the file. We  then call the ReadLine() method on the streamReader instance we created. 

The ReadLine()  method reads the whole line of characters and return the result as a string object. The result is stored in the dataLine variable. 

The value is then checked for null which checks if we have reached the end of the file. If this is not the case the value of the dataLine is output to the Console screen.

If a null is returned the loop condition fails and we don't attempt to read any further.

At the closing bracket of the using {....} construct the stream is disposed and the file to the handle is removed.

Note: Use the using {....} construct in you code to avoid memory leaks and fixing bugs later in the software life cycle.

Read the file in a single statement


If you don't want to read the file line by line, StreamReader provide another function to read data in a single go and return it as string. Use the ReadToEnd() method for such a scenario.

        private static void ReadTextFileAgain()
        {
            try
            {
                using (StreamReader streamReader = new StreamReader("d:\\data.txt"))
                {
                    string dataLine;
                    if ((dataLine = streamReader.ReadToEnd()) != null)
                    {
                        Console.WriteLine(dataLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: Unable to read the file");
                Console.WriteLine(ex.Message);
            }
        }



Sunday, October 9, 2016

CSharp Type Conversion

What is type conversion?


When a variable is declare and a value assigned to it, the compiler checks at compiled time whether the value being assigned to the variable will fit into the space allocated in memory to the variable. The type of the variable never changes during the scope of the program but its value can be used by other variables of a similar type with smaller or bigger space.


When you try to copy value of one variable to a different type some kind of conversion may be required. 




Forms of Conversion



Implicit Conversion

This type of conversion happens when a value being assigned in not bigger that the containing and is from the same branch. If you assign an integer value to a long variable an implicit conversion would happen. Suffice to say that the compiler would be happy to convert the int value to a long type and assign it to the variable of type long.

int x = 90899909;  //int is 4 byte 
long y = x;            //long is 8 byte

Explicit Conversion

This type of conversion requires the use of cast to tell the compiler that you required the conversion at your own risk of data loss. In this case you are assigning a value to a memory than does not fully fit and may get lost. When this is the case you need to explicitly cast the incoming value before assigning it to a smaller variable. 

You need to keep in mind that the target variable has a smaller memory so as long as the value you are assigning to it is within its range your code will work. If the value is greater than the range of the destination after conversion an arithmetic overflow may occur. 

An explicit conversion may also cause precision loss by rounding off values as we see in the example below that the decimal part (0.123) is lost.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aamirmehmood.tutorials.csharp
{
    class Program
    {
        static void Main(string[] args)
        {
            FloatToInteger();
        }

        private static void FloatToInteger()
        {
            float f = 2.123f;
            int x = (int)f;
            Console.WriteLine(string.Format("Value of f = {0}",f));
            Console.WriteLine(string.Format("Value of x = {0}", x));
            Console.ReadLine();
        }
    }
}


Output

Value of f = 2.123
Value of x = 2




Table showing numeric variable that require explicit conversions

(source MSDN: https://msdn.microsoft.com/en-us/library/yht2cx7b.aspx)

From             To

sbyte             byte, ushort, uint, ulong, or char

byte              Sbyte or char
short             sbyte, byte, ushort, uint, ulong, or char
ushort           sbyte, byte, short, or char
int                sbyte, byte, short, ushort, uint, ulong, or char
uint              sbyte, byte, short, ushort, int, or char

long
             sbyte, byte, short, ushort, int, uint, ulong, or char

ulong
           sbyte, byte, short, ushort, int, uint, long, or char

char 
            sbyte, byte, or short

float 
           sbyte, byte, short, ushort, int, uint, long, ulong, char, or decimal

double
         sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or decimal

decimal 
      sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or double


Conversions using built in methods


C# defines helper classes that you can use to convert variable from one type to the other type.

The System.Convert class provides many methods which you can use to convert one base data type to the other base data type.

Example of a using Convert class to convert a string to DateTime data type variable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aamirmehmood.tutorials.csharp
{
    class Program
    {
        static void Main(string[] args)
        {
            ConvertToDate("12-Oct-2016");
        }

        private static void ConvertToDate(string dateString)
        {
            DateTime date = Convert.ToDateTime(dateString);
            Console.WriteLine(string.Format("Value of date = {0}", date.ToString()));
            Console.ReadLine();
        }

    }
}




Friday, July 1, 2016

CSharp Literals

What are literals in C#



Define a literal

A literal is a fixed value. You can use it on the right hand side of an expression. You cannot assign a value to a literal. 

We discussed Left Hand Side (LHS) and Right Hand Side (RHS) in an earlier post. They are different from variables in that the variables can be placed on either side of the expression whereas the literals can be only on the right side of an expression.

int x = 3; //This is valid

3 = x; //This is not valid 


Types of Literals

Basically we can classify literals into numeric and non numeric literals.

String Literals

String literals are enclosed in double quotes "". Any number of characters can be placed withing the opening and closing quotation marks as long as you don't reach the memory limit of the data type.
string myName = "Aamir Mehmood";

string address = @"Unit# 123, 21 Street, \nOntario, \nCanada";

String literals can also contain escape sequence within quotes as shown above. 


Numeric Literals

When using numerical literals you use suffixes to specify the type of the value. Integer literal are suffixed with u, U, l, L, d, D, f, F, m, M


  • u and U are used for unsigned numbers
  • l or L are used for long numbers
  • d or D are used for double numbers
  • m or M are used for decimals numbers
  • f or F are used for floating point numbers


While the number 7 is an integer you can make it a double like so:

double y = 7D;




Other examples of numeric literals:


uint a = 45u;
long b = 479387L;
decimal g = 34.34m;


A short note on floating point literls is that the floating point numbers can be expressed in their decimal equivalent or exponential equivalent forms.



Example of decimal equivalent form


float fx = 3.4F; //If F is not applied the compiler will complain that you cannot assign 3.5, which is by default a double, to a float variable.

Example of exponential equivalent form

float ex = 1E-9;




Sunday, June 12, 2016

CSharp Data Types

Data Types in C#

C# is a strongly typed language. This means every variable you declare has a type associated to it. The types specifies the size and location of memory. The types available in C# are simple (a.k.a value) types and reference types.

Simple Types or Value Types

Value types are variables that are based on System.ValueType. These types actually contains the value in them. They are the boxes that keep the value inside the box. If the type of variable is any one of the built-in data types like int, char, string and so on, then that value of that variable will be stored on a stack which is a highly efficient memory.

C# Value or Simple Types

Name Size Range (Min - Max)
byte 8 bit integer (Unsigned) 0 to 255
sbyte 8 bit integer (Signed) -128 to 127
char 16 bit (Unicode) U+0000 to U+FFFF
int 32 bit integer (Signed) -2,147,483,648 to 2,147,483,647
uint 32 bit integer (Unsigned) 0 to 4,294,967,295
long 64 bit integer (Signed) –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong 64 bit integer (Unsigned) 0 to 18,446,744,073,709,551,615
short 16 bit integer (Signed) -32,768 to 32,767
ushort 16 bit integer (Unsigned) 0 to 65,535
double 15 to 16 digits precision ±5.0 × 10−324 to ±1.7 × 10308
decimal 28-29 significant digits (-7.9 x 1028 to 7.9 x 1028) / (100 to 28)
float 7 digits precision -3.4 × 1038to +3.4 × 1038
bool Boolean value true or false

C# Reference Types

Unlike value types that contain the value within them, reference types are variable whose value is a memory address. This memory address may actually point to the value stored on the heap.

Reference types are also called complex types in that you define it by combining one or more of the built-in or other reference types.

Complex types derive from Object type which is the base class for all reference types. We will look at Object Oriented Principles later in the series.

Reference types are housed in a heap memory and requires a non deterministic approach for memory management like garbage collection.

To put it simply, if you have an object of type Cat and you name it Daisy, here Daisy is a pointer to a place in the heap which contains the data for a type Cat. Lets look at an example.

public class Cat {
    public string name {get; set;}
    public string colour {get; set;}
}

The above code defines a Cat type with two attribute name and colour.

Cat daisy = new Daisy();
daisy.name = "Daisy Jr'";
daisy.age = 4;

The above 3 lines creates a Cat object whose reference name is daisy. This reference points to an object with two string values on the heap. If you create another Cat named kitty and assign the it daisy, then daisy and kitty will point to the same memory location on the heap.

 In simple words, reference types refer to something on the heap whereas a value types occupies its place on a stack.

Tuesday, May 3, 2016

CSharp Constants

What are constants

A constant also refers to name assigned to a memory in your computer like a variable but with a subtle difference; its value can only be assigned once. Yes, the value is assigned to the memory at compile time and it cannot be changed.




How do we declare constants in C#


Exactly like you declare variables but you put one extra prefix "const" to your declaration.

This is a variable declaration with assignment.

int speedOfLight = 299792458; /*meters per sec*/

You can change the value of the above variable.

speedOfLight = 670616629; /*miles per hour*/

This is a constant declaration with assignment.

const double pi = 3.14159265358979323846264338327950;

Assignment to a constant will cause a compile time error as you can only assign values to variables, properties or indexers.

Here comes the concept of lvalue and rvalue. Look at the example below:

lvalue = rvalue
x = 10; 

The lvalue is an expression that can be placed on the left or right of the expression.

In the expression x=10, the lavlue is x and rval is 10
x will have no problem if you write
int y = x; 

The rvalue of the expression can only be placed on the right side of the expressions.
So, if you write 10=x, this would not compile as 10 is not a variable, its a literal which can only sit on the right side.