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.


CSharp Variables

What are variables in general


In any programming language, a variable refers to a space in the computers memory. We give this space a meaningful name so that we can refer to that memory in our code easily without causing any confusion. 




Assigning a value to a variable means that we intend to put a value in the memory identified by the variable.


How to declare variables in C#


The syntax in C# to declare a variable is to first write the type and then its name like so:


typeOfVariable nameOfVariable;

            int counter;
            string name;
            double price;



Declare and Assign a value at the same time



You can declare and assign the value to a variable in a signle step like so:

typeOfVariable nameOfVariable = thevalueofthevariable;

These are some good examples of variable declarations with value assignment.

            int counter = 0;
            string name = "Your Name";
            double price = 24.99d;

These are some bad examples of variable as their names do seem to be meaningful:
            int x = 0;
            string theVariable = "Your Name";
            double p = 24.99d;

Saturday, April 30, 2016

CSharp Statements and Expressions

CSharp Statements and Expressions

In C# a statement is a line of code which form part of the program flow. Each line of code may perform an action or it may contain a non-action piece of code. Lets see how many types of C# statements we may write and then we will see a complete program using all these types of statements.

Types of Statements

  1. Declare Statements
  2. Assignment Statements
  3. Function Call Statements
  4. Return Statements
  5. Break Statement
  6. Conditional Statements
  7. Loop Statements

Expressions in C# are a combination of one or more variables, operators, a function call that would be processed and gives back a value. This value may be used by other expressions or contexts. Below are few examples of expressions

  • a>10
  • x = 2+3;
  • counter == 100
  • Math.Pow(2,4);


Lets try to understand them with example program. You can copy this program into a Visual Studio Console Application Project. Copy the code into Program.cs file and you are good to go. Hit F5 and you have an interactive application.

Example:


using System;
namespace SampleConsoleApp
{
    class Program
    {
        static void Main()
        {

            //Declare Statements

            double counter;

            string DoWhat; //1: Calculate Power, 2: Mutiply


            //Assignment Statements 

            counter = 10;
            DoWhat = "";

            while (true)

            {
                Console.WriteLine("");
                Console.WriteLine("Press One of these Options");
                Console.WriteLine("1. Power Calculation");
                Console.WriteLine("2. Multiples");
                Console.WriteLine("3. Say Hello");
                Console.WriteLine("0. Exit");
                DoWhat = Console.ReadLine();

                Console.WriteLine("You selected " + DoWhat);


                if (DoWhat.Equals("1"))  //Conditional Statements

                {
                    for (double i = 0; i < counter; i++) //Loop Statement and Expressions
                    {
                        PrintPower(i, (i - 2)); //Function Call Statement
                    }
                }
                else if (DoWhat.Equals("2"))  //Conditional Statements
                {
                    for (int times = 0; times < 5; times++) //Loop Statement
                    {
                        PrintMultiples(times, 6);//Function Call Statement
                    }
                }
                else if (DoWhat.Equals("3"))  //Conditional Statements
                {
                    SayHello();
                }
                else if (DoWhat.Equals("0"))  //Conditional Statements
                {
                    break; //Break Statement
                }
                else  //Conditional Statements
                {
                    Console.WriteLine("Invalid Input. Try Again");
                }
            }

            Environment.Exit(0);

        }

        private static void SayHello()

        {
            Console.WriteLine("Hello There");
        }

        private static void PrintMultiples(int i, int j)

        {
            Console.WriteLine("{0} x {1} = {2}", i, j, i * j);
        }

        private static void PrintPower(double i, double PowerOf)

        {
            try
            {
                Console.WriteLine("{0} to the power of {1} is {2}", i, PowerOf, Math.Pow(i, PowerOf));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Press Enter to EXIT");
                Console.ReadLine();
                Environment.Exit(1);
            }
        }
    }
}


Here is the program output





Tuesday, April 26, 2016

CSharp Your first CSharp program dissected

Your first CSharp program


Hello and Welcome to this C# multi-part series. We are going to start from the basics of C# language and get down to coding without getting deep into the history.


What you need to write and run the programs:
Download Free Visual Studio Community edition





















This is our first C# sample program.

 using System;

 namespace SampleConsoleApp
 {
   class Program
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Hello World");
         Console.ReadLine();
     }
   }
 }

Lets dissect it for a moment line by line.


1 using System; 


This is the bare minimum required by a C# executable. The statement means I want to use the namespace "System" and everything in it. Whats a namespace? Its a logical division of an application. Your code can exist in a single name space or span many. We will get to that in the next tutorials.


2 namespace SampleConsoleApp


This is my programs namespace called "SampleConsoleApp". This namespace contains the code that I wrote. 


3 {


Starting of my namespace "SampleConsoleApp"


4   class Program

I am declaring a class called Progam. You can use any name you like. Classes are simply template for objects that you create when needed. We will discuss classes and objects later in the course as part of object oriented programming.

5   {

Start of my namespace "Program"

6      static void Main(string[] args)

This is the entry point to the program. You can have only one Main method in this type of application. The string[] args is used to pass data that your program may need to run. You can also skip writing 

7      {

Start of my Main method

8         Console.WriteLine("Hello World");

Prints "Hello World" on the console.

9         Console.ReadLine();

Makes your program to wait for an input <ENTER>.

10      }

Ending of Main method

11   }
Ending of my namespace "Program"

12 }
Ending of my namespace "SampleConsoleApp"


To run this program just hit Ctrl+F5 or goto Debug menu and select Start Without Debugging on your visual studio and you should see "Hello World" on the console window.




Happy programming.


Please feel free to post comments, like and subscribe.