Archive

Archive for April, 2007

C# Tutorial : Lesson 05 – Encapsulation & Abstraction

April 9th, 2007
Encapsulation & Abstraction

Two concepts that go together in the object oriented approach are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of an object, while Encapsulation is the hiding of the non-essential features.

Think of a person driving a car. He does not need to know the internal working of the engine or the way gear changes work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much turning the steering wheel needs, etc (Abstraction).

Consider the example from the programmer’s perspective who wants to allow the user to add items to a list. The user only needs to click a button to add an item (Abstraction). The mechanism of how the item is added to the list is not essential for him (Encapsulation).

Below is a graphical representation of Encapsulation for the car class.

Implementing Encapsulation & Abstraction

Consider the countless advertisements being bombarded to viewers. The viewer does not listen to each one of them, rather only those he?s curious about. We use access specifiers to restrict the scope (visibility) of the class members.

Types of Access Specifiers
  • public – The members (Functions & Variables) declared as public can be accessed from anywhere.
  • private – Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber;
  • protected – Protected members can be accessed only from the child classes.
  • internal – Internal members can be accessed from anywhere within the application. This is the default access specifier for a class.

    Both these classes are equivalent.

    1
    2
    3
    4
    
    class MyClass
    {
     
    }
    1
    2
    3
    4
    
    internal class MyClass
    {
     
    }
  • protected internal – Similar to protected, protected internal members can be accessed from the child classes but only within the application.

Note: The members are always accessible to its own member functions, irrespective of the access specifier.

Lets see an example:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class House
{
	// Data Members
	public string DrawingRoom;
	private string Kitchen;
 
	// Member Functions
	private bool EnterDrawingRoom()
	{
		DrawingRoom = "The Drawing Room";
	}
 
	public bool EnterKitchen()
	{
		Kitchen = "The Kitchen"; /* Even though Kitchen is declared Private, EnterKitchen function
		can modify it because the member function itself has access to all other members. */
	}
 
}
 
class MainClass
{
	public static void Main()
	{
		House TheBlackHouse = new House();
		TheBlackHouse.DrawingRoom = "Main Drawing Room"; /* OK - Public Data Member is accessible
		from outside the class */
		TheBlackHouse.Kitchen = "Main Kitchen"; /* Error - Private Data Member is not accessible
		 from outside the class. */
		TheBlackHouse.EnterDrawingRoom(); /* Error - Private Member Function is not accessible
		// from outside the class. */
		TheBlackHouse.EnterKitchen(); /* OK - Public Data Member is accessible from outside
		the class. */
	}
}

Lets study the code. Inside the main function we declare an object TheBlackHouse of the House class. Thereafter, we set the value of the data member DrawingRoom for TheBlackHouse to “Main Drawing Room”. Since, DrawingRoom is declared as public, the above step works without any error. On the next line, TheBlackHouse.Kitchen = “Main Kitchen”; we are trying to assign the value “Main Kitchen” to the Kitchen variable of TheBlackHouse object. However, Kitchen is declared as private. Hence, this step generates an error.

In the next line, we are trying to call the private method EnterDrawingRoom for the object. This generates an error as well. Finally, we are calling the EnterKitchen function which is declared as public. Notice that inside the EnterKitchen function, we are assigning the value “The Kitchen” to the private variable Kitchen. This does not generate an error because the EnterKitchen method belongs to the same class and it has access to all the members inside the class, irrespective of the access specifier.

Why do we need Encapsulation, Abstraction?

Programming is all about concepts, different from coding where we basically translate the logic to language specific codes. When given a problem statement, there might be a number of ways to solve it. The logic devised to solve it will depend of the programmer. What we must learn to implement is the most efficient approach; efficient in terms of time, memory & cost. Object oriented methodologies such as these are what allow us to maintain efficiency.

By using encapsulation & abstraction, we reduce complexity by ignoring unimportant details and we maintain effectiveness by representing important ones.

partho C#

C# Tutorial : Lesson 04 – Object Oriented Programming

April 9th, 2007
Object Oriented Programming

Object Oriented Programming is a methodology modeled on real life. It comprises of the basic unit, an object, being used in implementing a program. Think of all the objects around you – cars, buses, birds, trees, etc. You will find countless ones of them, everywhere you go. In order to tackle this huge number, we started classifying them, thus came the term Class.

Class

A class is a composition of the theoretic characteristics (attributes and properties) of an object and the things it can do – behaviors, methods and features. Take the Car as an example. Its characteristics can include speed, color, number of gears, etc and it exhibits behaviors such as accelerate, brake and gear-change.

Object

An object is an instance of a class. Consider the Car class above, the Aston Martin that was used in the movie – Die another Day is an object of the car class. One point to note is that each object has at least one attribute that makes it unique.

Message Passing

Objects do not exist in isolation. They interact with other objects. These interactions take place through messages. Message passing is the process by which an object (sender) sends data to another object (receiver) or asks the other object to invoke a method. Thus, each message has a sender and a receiver.

Behavior

It is how an object acts and reacts, in terms of its state changes and message passing. For example, when the driver applies the break, the car comes to a stop.

This was all about the object oriented methodology. Now, let us take a look on how OOP is used in C#

Declaring Classes

We declare classes using the following syntax:-

class < Class Name >
{

data members…

member functions…

}

Here class is a keyword. Class name can be anything that follows the naming rules.

Rules for naming classes
  • A class name must begin with a letter & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
  • Special Characters such as ? – * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the class name.
  • A class name must not be the same as a reserved keyword such as using, public, etc.

Conventions for naming classes

  • Class Name must be meaningful, ideally a noun.
  • Naming of classes can be done using either the Pascal case, where the first character is capital and the rest are in small letters or using the Camel Case in which the first letter is in small case but the first letter of each successive word is in caps. Example:-
    • Pascal Case: Classone
    • Camel Case: classOne

The conventions are not mandatory but best practices, abiding by which allows others to easily understand our code.

Data members are the variables or other objects declared inside the class while member functions are the functions declared in it.

Example Class:-

class Student
{
	// Data Members
	public string Name;
	public int Age;
 
	// Member Function
	public void Display()
	{
		Console.WriteLine("Name {0}\n Age {1}", Name, Age);
	}
}

The public access specifier has been used in order to allow the data members & functions to be visible from outside the class. The access specifiers will be explained in the forthcoming tutorials.

Declaring & Instantiating Objects

Creating objects is similar to declaring variables and can be done using the syntax:-

<Class Name> <Object Name>;

Example: Student S1;

Before we start using the object, we need to instantiate it. Instantiation involves memory allocation and other basic initializations contained in the object’s constructor. We use the new keyword to instantiate objects. The syntax for which is given below:-

Note: Constructor is a special member function of a class that is used to initialize the data members. It will be dealt with, in later tutorials.

<Object Name> = new <Class Name>;

Example Usage: S1 = new Student();

These two steps can be done in a single line of code as Student S1 = new Student();

Using the Objects

We use the . (Dot) operator to access the members of the object. For example, to call the display method for the student class’s S1 object we write S1.Display();

Data members can be accessed in the similar fashion S1.Name = “Kenshin Himura”;

Releasing Memory

To release the memory occupied by the object we use S1 = null;

Example Program:-

using System;
 
namespace CSTutorials
{
	class Student
	{
		// Data Members
		public string Name;
		public int Age;
 
		// Member Function
		public void Display()
		{
			Console.WriteLine("Name {0}\n Age {1}", Name, Age);
		}
	}
 
	class Program
	{
		static void Main(string[] args)
		{
			Student S1;			 // Declaration
			S1 = new Student();	 // Instantiation
 
			Student S2 = new Student();	 // Single line Declaration &amp; Instantiation
 
			// Assigning value to member variables
			S1.Name = "Michael";
			S1.Age = 37;
 
			S2.Name = "Kimi";
			S2.Age = 25;
 
			// Invoking member function
			S1.Display();
			S2.Display();
			Console.ReadLine();
		}
	}
 
}
Benefits of Object Oriented Programming
  • Realistic Modeling: Living in a ‘World of Objects’, the model built on real life is a much better approach because it allows issues to be tackled with greater accuracy.
  • Re-usability of code: Think of a scenario where a car making company specialized in two seater’s decides to launch a four seater model. Converting the two seater model to a four seater is easier than designing a new model altogether.
  • Resilience to change: Being compartmentalized, individual objects can be improved without having to re-package the entire software.
  • Polymorphism: The behavior of an object can depend upon the state its in, thus exhibiting Polymorphism. Consider a car colliding with a wall. The impact of the process would depend upon the approach speed of the car, the Angle it strikes in, the strength of the wall and so on. If two cars were to collide, the results would be much different, with both of them receiving considerable damage.

partho C#

C# Tutorial : Lesson 03 – Programming Constructs

April 9th, 2007
Conditional Branching

By branching we imply, having different paths for execution. Conditions are used to determine which statements need to be executed. Suppose, you have a program to store the details of employees. Depending upon the post of the employee, there would be various fields associated with it. A department head, for example, would have a property denoting the department he heads, etc. We use conditional branching in such a scenario.

C# provides the following conditional constructs:-

if .. else

Syntax:-
if (<condition>)
{
statements
}
else
{
statements
}

The else part is optional and can be omitted. The working of if .. else construct is very simple and follows the pattern – If this is true I’ll do that or else I’ll do something else. The statements included within the if block are executed when the condition specified in if, is true, otherwise the statements inside the else block are executed. In case, there is no else statement, the execution flow continues to the proceeding statements.

Here’s an example:-

1
2
3
4
5
6
7
8
9
10
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
if (Age < 18)
{
	Console.WriteLine("You are not permitted in here.");
}
else
{
	Console.WriteLine("You may come in.");
}

Lets step through the code. Line 1 displays a message Enter your age. At line 2, the age entered by the user is read using ReadLine() (as a string) and converted to an integer using the ToInt32 function. Finally the value is stored in the integer variable Age. When the execution reaches line 3, the expression inside if is evaluated. If the user supplied an age less than 18, the execution flow would move to line 5 – Console.WriteLine(”You are not permitted in here.”); and the message You are not permitted in here would be displayed. In the other scenario, when the age would be either equal to or greater than 18, line 7 would be executed and the message You may come in will be displayed.

The condition inside the if statement can be composed of a complex expression chained by the logical operators. For Example:-

1
2
3
4
5
6
7
8
9
10
11
12
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Are you with your guardian? (True/False)");
bool WithGuardian = Convert.ToBoolean(Console.ReadLine());
if ((Age < 18 ) && (WithGuardian == false))
{
	Console.WriteLine("You are not permitted in here.");
}
else
{
	Console.WriteLine("You may come in.");
}

At line 4 the user’s response of whether he/she is with a guardian would be stored inside the boolean variable WithGuardian. Notice that ToBoolean function is used to convert the input to boolean (True/False) value. At line 5, the complex expression will be evaluated. The expression is made up of two sub-expressions: Age < 18 and WithGuardian == false. These two expressions are joined with the logical AND operator (&&). Therefore, when both of the expressions amount to true, the entire expression would evaluate to true and the message – You are not permitted in here will be displayed. For any other combination, the final expression would be equivalent to false and the message – You may come in will be displayed.

A number of conditions can be chained by using else if as follows:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Console.WriteLine("Enter your salary");
int Salary = Convert.ToInt32(Console.ReadLine());
if (Salary > 250000)
{
	Console.WriteLine("Welcome Mr. CEO");
}
else if (Salary > 200000)
{
	Console.WriteLine("Welcome Mr. Chairman");
}
else if (Salary > 0)
{
	Console.WriteLine("Welcome Programmer");
}
else
{
	Console.WriteLine("Welcome dear Customer");
}

In this case, if the salary supplied by the user is greater than 250000, the message – Welcome Mr. CEO will be displayed otherwise if the Salary is greater than 2000000 then the output will be Welcome Mr. Chairman else if the salary is greater than 0, the message – Welcome Programmer will be displayed. For any other value (Salary less than 1), the statements inside the else block would be executed and Welcome dear Customer will be the output.

switch .. case Construct

Switch case facilitates easy branching when the condition is pertaining to a single expression. Each supplied Value is preceded by a case construct.

Syntax:-
switch (<expression>)
{
case Expression_1;
statements
break;

case Expression_2;
statements
break;

}

break is a C# keyword, which is used to exit the body of a switch, for or while loop. Equivalent to the else construct is the default case. Statements within the default case are executed when no other condition holds true.

Example:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Console.WriteLine("Enter the month (mm)");
int Month = Convert.ToInt32(Console.ReadLine());
switch (Month)
{
	case 1:
		Console.WriteLine("January");
		break;
 
	case 2:
		Console.WriteLine("February");
		break;
 
	case 3:
		Console.WriteLine("March");
		break;
 
	case 4:
		Console.WriteLine("April");
		break;
 
	case 5:
		Console.WriteLine("May");
		break;
 
	case 6:
		Console.WriteLine("June");
		break;
 
	case 7:
		Console.WriteLine("July");
		break;
 
	case 8:
		Console.WriteLine("August");
		break;
 
	case 9:
		Console.WriteLine("September");
		break;
 
	case 10:
		Console.WriteLine("October");
		break;
 
	case 11:
		Console.WriteLine("November");
		break;
 
	case 12:
		Console.WriteLine("December");
		break;
 
	default:
		Console.WriteLine("There are only 12 Months.");
		break;
}

Depending on the value entered by the user (1-12), the appropriate month will be displayed. For any other value, the default case will be executed and the message There are only 12 Months. will be displayed.

Multiple Values can be made to lead to the same block of statements by excluding the break statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Console.WriteLine("Enter a number  (1-10)");
int Num = Convert.ToInt32(Console.ReadLine());
switch (Num)
{
	case 2:
	case 3:
	case 5:
	case 7:
		Console.WriteLine("The number is prime.");
		break;
	case 1:
	case 9:
		Console.WriteLine("The number is odd.");
		break;
	case 4:
	case 6:
	case 8:
		Console.WriteLine("The number is Even");
		break;
	default:
		Console.WriteLine("The number is not in range.");
		break;
}
Looping

A Set of instructions that are repeated is called a loop. Suppose you want to print numbers from 1 – 10. You could do that using Console.WriteLine statement for each of the 10 numbers. But, what if you had to print numbers from 1 – 1000? Using the computer’s iterative power is a much better approach.

C# supports 3 kinds of loops which are discussed below:-

The for loop

This loop is generally used for arithmetic operations, where we are aware of the starting and end point of the loop. Syntax of for loop is as follows:-

for(<initialization>;<condition>;<increment/decrement>)
{
statements
}

To print numbers within a range, say 1 – 1000, we declare a counter variable (preferably single character variable like I), initialize it to the starting number (1) and keep incrementing its value by 1 until the number exceeds the end point (1000). Off course, we would have the body of the loop where the operation would be done, in this case, displaying the numbers on screen.

1
2
3
4
for(int I = 1; I <= 1000; I  )
{
	Console.WriteLine(I);
}

Lets break the for statement down:-
Initialization: int I = 1
Condition: I <= 1000
Increment: I

All the parts here are optional and can be left out. So, you can initialize the variable I, above the for statement and leave out the initialization block. The code would look like this (; I <= 1000; I ). Similarly, you could remove the condition part to make the loop infinite or you can include the increment statement within the body of the for statement itself (inside the { and } brackets).

Another variation of a for statement is the empty loop which does not contain any body:-

for(int I = 1; I <= 1000; I++);

Such a for statement is followed by the semicolon.

The while loop

The for loop cannot be used when the range of the loop is unknown (Well, actually it can, but the approach would not be logical). Say, you want to continue inputting values from the user as long he wishes to. This can be easily implemented by the while statement.

Syntax:-
while(<condition>)
{
statements
}

We don’t have initialization and increment/decrement slot over here. These need to be implemented additionally. Take a look at the code snippet below.

1
2
3
4
5
6
7
8
9
bool Continue = true;
while(Continue == true)
{
	int A;
	Console.WriteLine("Please Enter a Number");
	A = Convert.ToInt32(Console.ReadLine());
	Console.WriteLine("Continue (True/False)");
	Continue = Convert.ToBoolean(Console.ReadLine());
}

We have declared a boolean variable Continue which we use to check whether to continue repeating the process. It has been initialized to true, so that the loop is executed for the first time. The user’s choice of whether to continue with the loop or not, is stored in Continue. As long as the user enters true, the statements within the body of the while loop would keep on executing.

Anything that can be implemented using for loop, can also be done using the while loop. Below is the code to print numbers from 1 – 1000 using while.

1
2
3
4
5
6
int I = 1;
while(I <= 1000)
{
	Console.WriteLine(I);
	I++;
}
The do while loop

The do while loop is a variation of the while loop in which the condition is evaluated at the end of the loop. Thus, the loop is executed at least once. Recall the first while program we did. The bool variable continue stores the user’s choice. However, for the first iteration, it does not store the choice. In such a scenario, we had to initialize continue with the value true so that the loop is executed for the first time. A better approach would be to use the do while loop and check the condition at the end. The code for which is given below.

1
2
3
4
5
6
7
8
9
10
bool Continue;
do
{
	int A;
	Console.WriteLine("Please Enter a Number");
	A = Convert.ToInt32(Console.ReadLine());
	Console.WriteLine("Continue (True/False)");
	Continue = Convert.ToBoolean(Console.ReadLine());
}
while(Continue == true);

Note: The while part in the do while loop needs to be terminated with the semicolon.

Although, either of the three types of loops can be used to do an iteration, one needs to use the appropriate loop for the job. Use the for loop for arithmetic operations, while loop for non-arithmetic ones and the do-while loop when the loop must execute at least once.

partho C#

C# Tutorial : Lesson 02 – Variables & Operators

April 9th, 2007
Variables

A Variable is a named location that stores a value. Although variables are physically stored in the RAM, their actual memory address is not known to the programmer. We can use the variables via the name we give them. These are the rules for naming a variable:-

  • The name must begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
  • Special Characters such as ? – * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the variable name.
  • A variable name must not be the same as a reserved keyword such as using, public, etc.
  • The name can contain any number of the allowed characters
  • Variables with the same scope cannot have the same name

Note: C# being a case-sensitive language, two variables such as var1 and Var1 would be different.

Any Variable has a type associated with it, which basically restricts the type of value it can store. The table below shows the Data types available in C#, the size they occupy in the memory and the values they can contain.

Type Size Range of values
char 2 0 and 65536
int 4 -2,147,483,648 and 2,147,483,647
float 4 -3.402823E+38 and -1.401298E-45 (For Negative Values)
1.401298E-45 and 3.402823E+38 (For Positive values Values)
double 8 -1.79769313486232E308 and 4.94065645841247E-324 (For Negative Values)
4.94065645841247E-324 and 1.79769313486232E308 (For Positive values Values)
bool 1 true or false
string Depends on length of the string 0-2 million Unicode Characters


Variable Declaration

Before we can use a variable, we need to declare it. Declaration of variables are done using the syntax:-
<Data Type> <Variable Name>;

For Example:-

1
2
3
4
int Age;
char Sex;
string Name;
bool IsMarried;

Variables of the same data type can also be declared using the syntax:-
<Data Type> <Variable 1>, <Variable 2>, .. and so on;

Example:-

1
int Age, RollNum;
Initialization

While declaring a variable, it is possible to assign an initial value to it. This operation is called Initialization and it has the following syntax:-
<Data Type> <Variable Name> = <Value>;

Example:-

1
2
3
4
int Age = 20;
char Sex = 'M';
string Name = 'Max Steel';
bool IsMarried = false;

Multiple variables of the same data type can also be initialized in a single line of code using the syntax:-
<data type> <variable 1> = <value>, <variable 2> = <value>;

1
int Age = 20, RollNum = 69;
Value Types

Values can be stored in variables by two methods which are: by value and by reference. Value types store the supplied value directly in the memory whereas reference types store a reference to the memory where the actual value is located. The benefit of the reference type is that changes made to any alias of the variable will reflect across all of its aliases.

Accepting Values in Variables

To input values from the user at runtime, we use the Console.ReadLine() function. For Example:- string FirstName = Console.ReadLine(); The above statement would declare a string variable FirstName and store the value retrieved from the user in it.

Note: Console.ReadLine() returns value as a string. Therefore, one must use type casting to convert the value to the required type. We use the member functions of the Convert class to do this. For Example: int Age = Convert.ToInt32(Console.ReadLine());. Similarly, there are other functions such as ToChar(), ToString, etc for conversion to other data types.

Operators

Similar to mathematics, every programming language has its own set of operators, be it arithmetic or logical. Operators enable us to perform operations on 1 or more values (operands) and calculate the result.

Usage

Depending on the number of operands they take, operators can be either unary or binary.
The use of an operator takes one of the following form:-

Unary Usage

  • <Operator> <Operand>
    Example: ++A;
  • <Operand> <Operator>
    Example: A++;

Binary Usage

  • <Operand 1> <Operator> <Operand 2>
    Example: A + B;
Classification

The operators in C# can be classified as follows:-

Arithmetic operators – Just what the name suggests, these operators are used to perform arithmetic operations.

Operator Usage Utility Type
+ A + B Add two numbers Binary
- A – B Subtract a number from another Binary
* A * B Multiply two numbers Binary
/ A / B Divide a number with another Binary
% A % B Remainder of the operation A / B Binary

Arithmetic Assignment Operators – These can be considered as shortcuts as they are used to perform both arithmetic and assignment operations in a single step.

Operator Usage Utility Type
= A = 69 Store the value 69 into A Binary
+= A += B Equivalent to A = A + B Binary
-= A -= B Equivalent to A = A – B Binary
*= A *= B Equivalent to A = A * B Binary
/= A /= B Equivalent to A = A / B Binary
%= A %= B Equivalent to A = A % B Binary

Increment / Decrement Operators – These operators are used to increment or decrement the value of an operand by 1.

Operator Usage Utility Type
++ ++A or A++

Increments the value of A by 1

Unary
--
--A or A--
Decrements the value of A by 1 Unary

Difference between Pre & Post Increment/Decrement
Consider the following code snippet:-

1
2
3
int A = 0;
int B = A++;
int C = ++A;

At the very first line, we have used the Arithmetic Assignment operator, = to assign the value of 0 to A. In the proceeding lines we have used both Pre & Post increment. At line 2 int B = A++; the operation being post increment, the value of A i.e 0 is assigned to B followed by the increment of A’s value. At line 3 int C = ++A; the current value of A, i.e. 1 is incremented by 1 following which the new value of A is assigned to C. Therefore, the value of A = 2, B = 0 and C = 2.

What will be the output of the following code?

1
2
3
int A = 5;
int B = (A++) + (--A);
Console.WriteLine("Value of B = {0}", B);

At line, 1, A gets initialized to 5. The next line is a bit tricky. Here, The RHS should be evaluated like 5 + 4 because A++ is post increment and this operation should occur after the line of statement. But, this is not the case, instead it takes place in the same line but after the evaluation of the sub-expression (A++). Hence, the expression will be evaluated as 5 + 5 and the output will be 10.

Comparison Operators – These operators are to compare two values and return the result as either ‘true’ or ‘false’.

Operator Usage Utility Type
< A < B

Compares if A is less than B

Binary
> A > B Compares if B is less than A Binary
<= A <= B Compares if A is less than or equal to B Binary
>= A >= B Compares if A is greater than or equal to B Binary
== A == B Compares if A is equal to B Binary
!= A != B Compares if A is not equal to B Binary

Logical Operators – These operators are used to perform logical operations and return the result as either ‘true’ or ‘false’.

Operator Usage Utility Type
&& A && B

Returns true if Both A and B are true

Binary
|| A || B Return true if either A or B are true Binary
! !A Returns True if A is false Unary
^ A ^ B Returns true when A and B do not match i.e one is true and the other is false Binary


Displaying Variables

We us the WriteLine method to display the value stored in variables.

Displaying Single Variable

1
2
int A = 6;
Console.WriteLine(A);

Displaying Multiple Variables

1
2
int A = 6, B = 9;
Console.WriteLine("{0},{1}", A, B);

Notice the code “{0},{1}”. This is the format for the output to be generated by WriteLine. Since, we are displaying two variables, we need to specify the format accordingly. Here {0} and {1} represent where the proceeding variables A & B will be displayed. Now take a look at the following code snippet:-

1
2
int A = 6, B = 9;
Console.WriteLine("The value of A = {0} and B = {1}", A, B);

The output of these lines would be: The value of A = 6 and B = 9. As you can see, the {0} and {1} are replaced by the variables A and B. 0 and 1 correspond to the index of the variables following the format, starting from 0.

Comments

Software applications are made by a group of coders. Each one of them handles various aspects of the application. Its important to write descriptive texts in order to help other coders understand, the mechanism of the codes you have written. We use comments denoted by // or /* and */ for this very purpose. Example usage:-

1
2
3
// This is a comment
/* These are two lines
of comments */

Note: The compiler ignores all comment entries. // is used for single line of comment while /* and */ are used for multiple lines.

What’s in a Semicolon?

Whitespace except when used inside quotes, is ignored in C#. All statements in C# are terminated by using the semicolon. This allow spanning of codes across multiple lines.

The following lines of code are functionally equivalent.

1
int A = 6, B = 9; Console.WriteLine("A   B = {0}", A   B); Console.ReadLine();
1
2
3
int A = 6, B = 9;
Console.WriteLine("The sum of {0} and {1} = {2}", A, B, A   B);
Console.ReadLine();

partho C# , ,