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

C# , ,

Linking: Static & Dynamic

March 6th, 2007

When we compile a program, the code for the various in-built functions are copied from the appropriate libraries. This process of linking of library functions during compilation is called Static Linking.

The process of linking of library functions during runtime is called Dynamic Linking. In Dynamic Linking, the code for the functions are not copied during compilation, rather only a reference to them is added. At runtime, the reference is resolved (when needed) and the code inside the library where the function definition exists is given the control. After completion the control is passed to the application.

Note:- Control here implies the flow of execution.

Dynamic Linking has various advantages when compared to static linking:-

  • Smaller Size of Compiled Application: The function definitions
  • Easy Updation: The program does not need recompilation if the library is updated.
  • Better Memory Usage: A Library can be shared by multiple programs, thus the memory requirement is reduced.

A compiled library file has an extension .dll which stands for Dynamic Link Library.

General

Linking: Static & Dynamic

March 6th, 2007

When we compile a program, the code for the various in-built functions are copied from the appropriate libraries. This process of linking of library functions during compilation is called Static Linking.

The process of linking of library functions during runtime is called Dynamic Linking. In Dynamic Linking, the code for the functions are not copied during compilation, rather only a reference to them is added. At runtime, the reference is resolved (when needed) and the code inside the library where the function definition exists is given the control. After completion the control is passed to the application.

Note:- Control here implies the flow of execution.

Dynamic Linking has various advantages when compared to static linking:-

  • Smaller Size of Compiled Application: The function definitions
  • Easy Updation: The program does not need recompilation if the library is updated.
  • Better Memory Usage: A Library can be shared by multiple programs, thus the memory requirement is reduced.

A compiled library file has an extension .dll which stands for Dynamic Link Library.

General

Event Driven Programming

March 5th, 2007

Prior to the Event Driven model, programming was procedural, where there would be an entry point for the application, typically known as the main function. From there, the flow of execution could be branched to different modules depending upon conditions such as inputs from the user. In an Event Driven Paradigm, the execution is not necessarily continuous. The statements that will be executed depend on the events. The events could be user generated: Clicking a Button, Closing a Window, Moving the mouse over a contol and so on, or system generated such as elapsing of a timer’s interval.

We write codes corresponding to these events which are executed when ever the event takes place. For example, the following code shows a dialog box with the message “Hello World” when the Show button is clicked:-

private void ShowMessage_Click(object sender, EventArgs e)
{
	MessageBox.Show("Hello World");
}

Notice the words object sender, EventArgs e, these are the parameters being passed along with the event. These parameters are used to determine the state of the control. In the following example, the KeyPressEventArgs being passed along with the event, is used to determine the key that was pressed in a text box.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
	MessageBox.Show(e.KeyChar.ToString());
}

General

Introduction to User Interface

March 5th, 2007

User Interface is the layer between the User and the Application that enables the user to interact with the application. User Interfaces are either Console (CUI) or Graphical (GUI).

In a Console User Interface such as the one shown below, the user needs to use pre-defined commands to interact with the application. In general, the keyboard is used for input.

CUI

Unlike in a CUI, the user does not need to remember commands for interacting with the application, rather various controls are used for the same. Also, pointing devices such as the mouse are used along with the keyboard.

GUI

There are various types of controls to help us in enabling the User to interact with our application. Below is an image showing a few of the pre-defined controls.

GUI

Only container controls can exist on their own. All other controls have to reside inside containers.
Note: A container can also contain another container.

In the previous image, the Window which contains all the controls viz Label, Button, Text Box, etc, is the container we call Windows Form. A Dialog box is a special type of Form that is used to group related controls. Typically, the dialog boxes are used to notify an event or error, ask for an input, etc.

GUI

Dialog boxes are of three types:-

Modal

A modal dialog box does not allow you to switch focus to another area of the application (unless it is closed). For Example, the Save As Dialog box in Paint.

GUI

Modeless

A modeless dialog box allows you to switch focus to another area of the application. For Example, the Find & Replace dialog box in Notepad.

GUI

System Modal

A system modal dialog box is a system wide modal dialog box which does not allow the focus to be switched to any other application.

GUI

General

Recoverable Data Storage

February 27th, 2007

Ever felt helpless at the hands of the Cyclic Redundancy Check (CRC) error? Here’s what you should do to keep it at bay.

A cyclic redundancy check (CRC) is a type of hash function used to produce a checksum – a small, fixed number of bits – against a block of data, such as a packet of network traffic or a block of a computer file.

Source: Wikipedia

Storing files in the form of compressed RAR format has benefits beyond just solid compression. Most notably, the ability to split archives and recover data from corrupted ones. WinRAR is a lightweight, easy to use and powerful RAR archiver. It can be obtained from Rar Lab. While creating compressed archives, select the put recovery record option.

Put Recovery Record

Putting the recovery record allows the recovery of data from damaged archives in most of the cases. The overhead data added is very less, generally 1 – 2 percent. Despite the extremely small size, the reliability it adds is really amazing. Around 75% of damaged archives are recoverable.

Data stored in removable media such as CDs become corrupt with wear & tear. Sometimes, in spite of imparting great care, the files may become unreadable. The problem is heightened when the size of the files are quite large, as a few unreadable sectors would render the file unable to be copied. Thankfully, there are softwares to recover such files. CDCheck is one such handy tool. It extracts whatever amount of data that can be read and pads up the ones which can’t. Thus allowing even files with CRC errors to be saved locally.

Using CDCheck and WinRAR (with ‘Put Recovery Record’) in conjugation is a highly safe way of backing up data.

Tips

C# Tutorial : Lesson 01 – Hello World Program

February 14th, 2007

This is the first installment of my venture to explain the bits and pieces of C# that I have managed to learn at NIIT. In this lesson we would be creating the Hello World application.

First Step: Create a New Console Application in Visual C#

The IDE automatically adds the following code:-

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Text;
 
namespace HelloWorld
{
	class Program
	{
		static void Main(string[] args)
		{
		}
	}
}

Lets take a look at the first 3 lines. All of these lines begin with the keyword using. A namespace is an abstract collection of classes. The .NET Framework has a huge set of classes. They are grouped under namespaces for easy accessibility, better categorization and to prevent name clashing. For Example, the System.IO namespace contains all the classes, functions & methods required for Input Output operations, thus making life easier for us human beings. While the namespaces have remarkable benefits, they tend to bring in some potential inconveniences too. Take the System.Console.WriteLine() method for example. The method has to be called along with its complete path in the hierarchy, a really tiresome process to do repeatedly. This is when the using keyword comes into aid by importing the namespaces. When imported, the classes inside the namespace can be accessed just by their names. So, once we have imported the System namespace, the above method can be called as Console.WriteLine().

Any .NET application that we make, has to reside in a namespace of its own, so we write the statement namespace HelloWorld. All the classes you create under this namespace can be accessed as NameSpaceName.ClassName.

Next we have the class declaration itself. Inside you’ll find the static void Main function. This is the entry point for the application. Think of it as the outer door of your house. Any one coming inside has to first pass through it. The entry point must be declared as static because that way the main function can be invoked even without creating an object of the Program class. Also the name of the entry function should be Main, the capital M counts too.

Any application can take parameters, when run from the command prompt. Say you ran the Notepad application as follows Notepad.exe MyFile.txt. The text MyFile.txt is the parameter passed to it, Notepad reads this parameter and opens the file. Similarly, we may need to work with arguments passed to our application. This is why we use the string[] args inside the Main function.

Up until this point I have described the auto generated code. Now let us type in some code of our own. Keeping with the tradition of the Hello World program we type in Console.WriteLine(“Hello World”); inside the body of the Main function. The Console class resides in the System namespace and represents the standard input, output and error streams for console application. The WriteLine method displays the supplied argument(s) on the console.

Press F5 to run the application. You’ll see a console window with the text Hello World appear. Don’t worry if the window closes on its own. Its because the application reaches the end point and exits. You can add the following line to make it halt for an input before exiting: Console.ReadLine();

This is how our final code looks like:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Collections.Generic;
using System.Text;
 
namespace HelloWorld
{
	class Program
	{
		static void Main(string] args)
		{
			Console.WriteLine("Hello World");
			Console.ReadLine();
		}
	}
}
Escape Sequences

Much like C/C++ , C# has a list of escape sequences. Escape Sequences or Escape Characters are some special characters which cannot be displayed directly. For Example, the newline character or the Double Quotes.

White space being ignored by C#, the newline escape sequence is the only way to display the newline character in the output. The double quotes are used to enclose strings hence they cannot be used directly. To display the special characters such as these, we use escape sequences. All escape sequences begin with the backslash character \

Example Usage:-

Console.WriteLine("This is a \n multi-line text");

Output:-
This is a
multi-line text

Console.WriteLine("C# is a \"Programming Language\"");

Output:-
C# is a “Programming Language”

Here’s the list of the escape characters in C#

Escape Sequence Equivalent Character
\’ Single Quotation
\” Double Quotation
\\ Backslash
\0 NULL
\a Alert
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab

Note: Equivalent for Visual Basic’s vbCrLf is \r\n

C#

Non Repeating – Random Number Generation Class

February 8th, 2007

Sometimes, we require to generate non-repeating random numbers. Here’s the code I wrote to do just that. The numbers to be generated can be within the specified range or passed as a param array.

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
Public Class RandomNumber
    Dim NumDomain As New ArrayList      ' The Numbers to be generated
    Dim Nums As New ArrayList           ' The Numbers waiting to be generated
 
    Sub New(ByVal Start As Integer, ByVal Finish As Integer)
        ' Sequential Numbers
        Dim I As Integer
        For I = Start To Finish
            NumDomain.Add(I)
        Next
 
        AddItems()
    End Sub
 
    Sub New(ByVal ParamArray Numbers() As Integer)
        ' Numbers in a Param Array
        Dim Number As Integer
        For Each Number In Numbers
            NumDomain.Add(Number)
        Next
 
        AddItems()
    End Sub
 
    Private Sub AddItems()
 
        Nums.Clear()
        ' Insert All Numbers Into the Array
        Dim I As Integer
        For I = 0 To NumDomain.Count - 1
            Nums.Add(NumDomain(I))
        Next
    End Sub
 
    Public Function GetRandomNumber() As Integer
        If Nums.Count = 0 Then
            ' Re-add the Items, when all the numbers have been generated.
            AddItems()
        End If
 
        ' Return a Random Item and Remove it from the List
        Dim Ch As Integer
 
        ' Using Timer as the seed for the Random Number Generation
        Randomize(Microsoft.VisualBasic.Timer)
 
        ' Random Number is generated within the range.
        Ch = 0 + CInt(Rnd() * (Nums.Count - 1))
 
        Dim Num As Integer = Nums(Ch)
        Nums.RemoveAt(Ch)
        Return Num
    End Function
End Class
Mechanism

The overloaded constructors allow numbers to be generated either within a range or from the numbers passed as parameters. Internally there are two array lists: NumDomain & Num. The former contains all the numbers within the domain and the latter holds the numbers that have not been generated. The GetRandomNumber function returns a random number from the Num array list and also removes it from there. When all the numbers have been poped (not to be confused with stack poping) out, the Num array list is re-filled with the values in NumDomain and the cycle continues. Thus, allowing no repeats per cycle.

Visual Basic

Notepad++

February 8th, 2007

Notepad++Notepad++ is a free, light weight but powerful editor which supports several programming languages, running under the MS Windows environment. With features such as syntax highlighting and folding, full drag & drop support, auto completion, regular expression search/replacement this tool is a must have. It can also be set as the default HTML editor, so when you click on View > Source under Internet Explorer, the HTML code will open with Notepad++. Another plus point is that it has a plugin architecture which allows further extendability. One of the bundled plugins is a Hex Editor.

This project, based on the Scintilla edit component (a very powerful editor component), written in C++ with pure Win32 API and STL (that ensures the higher execution speed and smaller size of the program), is under the GPL Licence.

Quick Links:-

Freeware

The Essence of Visual Basic

February 7th, 2007

Simplicity and ease of use, is what makes Visual Basic the most popular programming language in the World. Introduced as the Rapid Application Development (RAD) Tool, Visual Basic gained much fame because of the innovative features it pioneered:-

The name visual itself is very important, for the first time, people could drag and drop controls onto a design surface and see how a program would look without going through the lengthy edit-compile-test cycles required by other languages.

Stepping Through Code

Stepping through code while debugging – just ask any VB developer if they could do without it.

Stepping Through

The introduction of Active X Controls took the idea of code re-usability to a completely new level. VB was also the first popular general-purpose language to offer truly integrated database access. The IDE concept that VB revolutionized has now been incorporated by non Microsoft products too (Delphi, Java).

Intellisense

It speeds up software development by reducing the amount of keyboard input required and allows less reference to external documentation due to embedded function signatures and short descriptions.

Intellisense

Case Insensitivity

Nothing personal against the shift key, but holding it up and down is really annoying. Try typing miCRoSCoPiC^eaRthLinG for a change.

Shift Key

True it lacked the pure object oriented power of other languages, but hasn’t it caught up with the new .NET version? As we programmers grow lazier day by day, changes such as these are immensely welcome and with the further advent of hi-tech sidekicks, we will do so even more.

General