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.