Tuesday, 25 March 2014

3: Statement, Expression and Operators in C#

Statements in C#

Statements are used for input, process and output task of a program.

Examples:

Console.WriteLine(“Statements in C Sharp”);
Int stateRange=5;
Mystate obj=new  Mystate();
String Name=Console.ReadLine();

Types of Statement:

There are four basic statements in C#.
  1. Selection Statement
  2. Iteration Statement
  3. Jump Statement
  4. Error/Exception Handling statement

1. Selection Statement

Selection statements uses if, else, else if, switch and case. These type of statements are use for taking decision.

2. Iteration Statement

Iteration statements uses do, for, foreach, in and while. These types of statement are used for repetition of block (block of code).

3. Jump Statement

Jump statement uses break, continue, default, goto, return and yield. These types of statement are used for transferring the flow from one block to the another.

4. Error/Exception
Error/Exception uses throw, try-catch, try-finally and try-catch-finally. These types of statement are used for creating custom exception, and catching run time error/exception.


Expression in C#

Expression in C# is use for manipulation of data.

Example:

(10*10)+ (12-2);
Expression always returns value.
Expression is a part of Statement.
int myStateExpression=(10*10)+(12-2);

Operators in C#

There are six types of operators in C#.
  1. Arithmetic operators
  2. Relational operators
  3. Logical operators
  4. Conditional operators
  5. Increment and decrement operators
  6. Assignment operators

Arithmetic operators

There are four operators use for performing arithmetic operations. +, -,*,/,%.
Example:

Relational operators

There are six operators use for comparison between two operands. And return true or false based on the condition.
== equal to, != not equal to, > greater than, < less than, >= greater than and equal to, <= less than and equal.


Example:

Logical operators

Logical operators are binary operator use to perform logical operations and return true or false (Boolean value).
Operators are & (AND operator), | (OR operator) and (Exclusive OR).

Example:

Conditional operators

There are two types of Conditional operators

Conditional AND (&&)
In conditional AND, if first expression true then it check next expression otherwise return false.


Conditional OR (||)
In Conditional OR, if first expression false then it check next expression otherwise if it finds true at first expression it does not check second expression and return true.
Conditional operators can be explain by following example.

Example:
string sName1 = "Ahmad";
string sName2 = "Faraz";

Console.WriteLine("Ahmad and Faraz are there = {0}",(sName1=="Ahmad" && sName2=="Faraz"));// return true because both expression true

Console.WriteLine("Ahmad and Faraz are there = {0}", (sName1 == "Waqas" && sName2 == "Faraz"));// return false because first expression false

Console.WriteLine("Ahmad and Faraz are there = {0}", (sName1 == "Ahmad" && sName2 == "Wasim"));// return false because second expression false

Console.WriteLine("Ahmad and Faraz are there = {0}", (sName1 == "Ahsan" && sName2 == "Wasim"));// return false because both expression false

Console.WriteLine("Ahmad or Faraz are there = {0}", (sName1 == "Ahmad" || sName2 == "Faraz"));// return true because first expression true, not see second

Console.WriteLine("Ahmad or Faraz are there = {0}", (sName1 == "Waqas" || sName2 == "Faraz"));// return true because second expression true

Console.WriteLine("Ahmad or Faraz are there = {0}", (sName1 == "Ahmad" || sName2 == "Wasim"));// return true because first expression true

Console.WriteLine("Ahmad or Faraz are there = {0}", (sName1 == "Ahsan" || sName2 == "Wasim"));// return true because first expression true


Increment/Decrement operators

Increment/Decrement operators are use for increment by one or decrement by one.
Denoted by ++, --. If ++/-- found before variable so it called pre-increment/pre decrement respectively.
If ++/-- found after variable so it called post-increment/post decrement respectively.

Example:
int age = 22;
Console.WriteLine("After one year my age is {0}",++age);//example of pre-increament
Console.WriteLine("last year my age was {0}", --age);//example of pre-decrement


Assignment Operators

Assignment operators are use to assign value from right side operand to the left side operand.
There are two types:
Simple assignment operator is denoted by “=”.
Name=”my Name”;
Compound assignment operators use “=” and arithmetic operator.
Like +=, -=, /=, *= etc.

For example:
int a = 10;
a += 10;
Console.WriteLine(a);
a -= 10;
Console.WriteLine(a);

Use all like above example for learning.



Monday, 24 March 2014

2: Variables, Datatypes and Their Usage in C#

What is Variable?

A variable is entity whose value can keep changing.
For example, the age of a person, and increment or salary of an employee
In c#, the memory is allocated at the time of variable creation.

Syntax:
<data type><variable name> // declaring variable
<variable name>// initialization

Let’s talk about the name and age of a student.
As you learn before in C languages Name should be string, and age should be integer
So,
String studentName;
studentName=”Muhammad Wasim”;
int studentAge;
studentAge=23;

Observe that the first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. E.g. studentName, studentAge this is called camel notation. Microsoft recommends camel notation for C# variables, do not use reserved keywords, see reserved keywords

http://msdn.microsoft.com/en-us/library/x53a06bb.aspx

Data types:

When you go to shop for buying milk and flour etc. the shopkeeper always give you milk in water proof bag but do not give you in normal paper bag like he gives flour. Similarly the compiler does not know which type of data you want to give it. It may be string type or integer type or character etc.
When you declare a variable the data type is assign to the variable like in below example.

String studentName;

In C# data types are divided into two types,

 1) Value type
 2) Reference type

Value type
Variable of value types are stored in stack. These variables store actual values, these values can either be user define or predefined data type.
Most of the built-in data types are value type like int, float, double, char bool etc.

Reference type
Variable of reference type store the memory address of other variable in a heap, these values can either be user define or predefined data type.

Like string is built-in data type but it is reference type, but most of the user define data types are reference type like class, interface, array, and delegate.


We will talk about all the reference type later in our coming posts.
Let’s talk about student class. We will see class later in depth.

Here you can see student class is stored in heap(heap located in  RAM) which is reference type and its variable(studentAge) is value type.

Predefined Data type


Literals in C#

A literal is a static value assign to the variables. We can define literals for any data type in C sharp.

Types:            

  1. Boolean Literal
  2. Integer Literal
  3. Real Literal
  4. Character Literal
  5. String Literal
  6. Null Literal

Boolean Literal:
Boolean literal have two values, false, true
Bool myBoolValue=false;
Where false is a boolean literal assign to the boolean literal.

Interger Literal:
Integer Literal can be assign to int, long etc data types.
Suffixes are U, L, UL or LU where U is use for uint or ulong, L is use for long and LU or UL is use for ulong.
long myLongValue=1000L;
Where 1000L is a integer literal assign to the myLongValue variable.

Real Literal
A real literal can be use for float, decimal  and double.
Suffixes are F, D and M where F is use for float, D is use for Double and M is use for Decimal.
Float myFloatValue=4.54F;
Where 4.54F is a real Literal assign to the myFloatValue variable.

Character Literal
Character Literal can be use for character data type.
It is simple define as
char myCharValue=’w’
where w is a character literal assign to the myCharValue variable.

String Literal
There are two types of string Literals
  1.   Regular string literal
  2.   Verbatim string literal
Regular can be define as
string myStringValue=”Dot Net”;
Verbatim is similar to the regular string Literal but it start with @ symbol.
string myStringValue=”@hotmail.com”;

Null Literal
Null literal is only one value which is “Null”
string myNullValue=null;

Character Escape Sequence in C#

Character Escape sequence is use for formatting the string data.

Here are some examples using Character Escape Sequence you can use above escape sequence for learning .

Console.WriteLine("Muhammad\nwasim"); //new line operator
Console.WriteLine("Welcome \'Friends\'");// single quote
Console.WriteLine("laptop\t PC");// tab sequence

Merging and Concatenation
Merging are concatenation are two ways for formatting text when using Console.WriteLine() method.

PlaceHolder

PlaceHolder is use for concatenate the text before display the output,
It use braces with zero based index to indicate the position of suitable value
For example:
int num1=10;
int num2=5;        
Console.WriteLine("Number one is {0} and Number two is {1}",num1, num2);

Merging can also perform the above operation without using index for position of the suitable variable.
Below example works similar to the above example

Console.WriteLine("Number one is " + num1 + " and Number two is " + num2);


Taking Value From User



In C language you simply define in Scanf() function the type of data that should be taken by the user but in c sharp there is no such a function but there is a method called Console.Readline() which always take string value from the user.



Example:

string name;
Console.WriteLine("Please Enter Your Name");
name = Console.ReadLine();
Console.WriteLine("your Name is {0}",name);
Console.ReadLine();

Notice that we have taken value in string name variable at this point the cursor waits for input see below 

What Happen when you get inter value from Console.ReadLine() method.


Yes it show compile time exception which is “Cannot implicity convert type string to int”, as I define above that Console.ReadLine() only take string value from the user not like scanf() in C.
This issue can be remove by the convert class for converting string to integer.

Convert class provide you many method like ToDouble, ToChar, ToDecimal etc you can explore more pressing ‘.’ After writing Convert
Soon We Will See Type Casting and its Types.