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);
            }
        }