C# Introduction

C#(pronounced as see sharp) programming language encompassing strong typing, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed by Microsoft within its .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2006). C# is one of the programming languages designed for the Common Language Infrastructure. C# is intended to be a simple, modern, general-purpose, object-oriented programming language. Its development team is led by Anders Hejlsberg. The most recent version is C# 6.0, which was released on 15, 2015.

C# is one of several languages(like vb.net,JScript) that target the Microsoft Common Language Runtime (CLR). Languages that target the CLR benefit from features such as cross-language integration and exception handling, enhanced security, a simplified model for component interaction, and debugging and profiling services. Of today’s CLR languages, C# is the most widely used for complex, professional development projects that target the Windows desktop, mobile, or server environments.

Brief History

In January 1999, Anders Hejlsberg formed a team to build a new language at the time called Cool, which stood for "C-like Object Oriented Language". Microsoft had considered keeping the name "Cool" as the final name of the language, but chose not to do so for trademark reasons. By the time the .NET project was publicly announced at the July 2000 Professional Developers Conference, the language had been renamed C#, and the class libraries and ASP.NET runtime had been ported to C#. C#'s principal designer and lead architect at Microsoft is Anders Hejlsberg, who was previously involved with the design of Turbo Pascal, Embarcadero Delphi (formerly CodeGear Delphi, Inprise Delphi and Borland Delphi), and Visual J++. In interviews and technical papers he has stated that flaws[citation needed] in most major programming languages (e.g. C++, Java, Delphi, and Smalltalk) drove the fundamentals of the Common Language Runtime (CLR), which, in turn, drove the design of the C# language itself. James Gosling, who created the Java programming language in 1994, and Bill Joy, a co-founder of Sun Microsystems, the originator of Java, called C# an "imitation" of Java; Gosling further said that "[C# is] sort of Java with reliability, productivity and security deleted. Klaus Kreft and Angelika Langer (authors of a C++ streams book) stated in a blog post that "Java and C# are almost identical programming languages. Boring repetition that lacks innovation, "Hardly anybody will claim that Java or C# are revolutionary programming languages that changed the way we write programs," and "C# borrowed a lot from Java - and vice versa. Now that C# supports boxing and unboxing, we'll have a very similar feature in Java." In July 2000, Anders Hejlsberg said that C# is "not a Java clone" and is "much closer to C++" in its design. Since the release of C# 2.0 in November 2005, the C# and Java languages have evolved on increasingly divergent trajectories, becoming somewhat less similar. One of the first major departures came with the addition of generics to both languages, with vastly different implementations. C# makes use of reification to provide "first-class" generic objects that can be used like any other class, with code generation performed at class-load time. By contrast, Java's generics are essentially a language syntax feature, and they do not affect the generated byte code, because the compiler performs type erasure on the generic type information after it has verified its correctness.

 

A Simple C# Program

There are basic elements that all C# executable programs have and that's what we'll concentrate on for this first Topic, starting off with a simple C# program. . Please see Listing 1-1 to view this first program and fallow below steps to execute it .

There are some steps to implement (Run) this concepts on Notepad Which are given below:- Step 1:- First open Your Notepad -->Copy and Paste below code or write your own program:-

Note: C# is case-sensitive.(there is difference between lowercase & upercase)

Listing 1-1. A Simple Welcome Program: FirstProgram.cs
//Namespace Declaration
using System;
//Program start class
class WelcomeCSS
{
// Main begins program execution.
static void Main()
{
// Write to console
Console.WriteLine("Welcome to the C# Faith Tutorial!");
}
}
Step 2:- Now save the Notepad program in any drive with .cs extension (i have saved in D:\Topic01\FirstProgram.cs file ) as shown below:-

Step 3:- Now open Visual studio Command prompt from start Menu or taskbar-->first give the drive path(ex-D: PRESS ENTER) -->Compile the program->csc->space-> foldername \ filename.cs (e.g. csc Topic01\FirstProgram.cs) -->you will see one .exe file(FirstProgram.exe) generated in your Drive as shown below in steps:-





Step 4:- Now Run the program as filename.exe (FirstProgram.exe) as shown below:-

or just double click on FirstProgram.exe file

The program in Listing 1-1 has mainly 4 primary elements, a namespace declaration, a class, a Main method, and a program statement. It can be compiled with the following command line:

 csc.exe FirstProgram.cs

This produces a file named FirstProgram.exe, which can then be executed. Other programs can be compiled similarly by substituting their file name instead of FirstProgram.cs. For more help about command line options, type "csc -help" on the command line. The file name and the class name can be totally different.

VS.NET Users:


The screen will run and close quickly when launching this program from Visual Studio .NET. To prevent this, add the following code as the last line in the Main method: Here are steps to run same program in Visual studio






// keep screen from going away // when run from VS.NET Console.ReadLine();

A Closer Look at Your Program

Now that we've got our program running, let's take a minute and look at each of the lines of code in the program we've got. I'll try to explain what each one does, so that you'll have a basic understanding of everything that you've got in your simple "Hello World" program.

Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

The first few lines of your program all start with the keyword "using". A keyword is simply a reserved word, or a magic word that is a built-in part of the C# programming language. It has special meaning to the C# compiler, which it uses to do something special. The using keyword tells the compiler that there is a whole other pile of code that someone else has written (in our current case, it was written by the guys over at Microsoft) that we want to be able to access.

So when you see something that looks like this: using System;, you know that there is a whole pile of code out there, that is called "System", which our code will want to use. Without this line, the C# compiler won't know where to find certain things, and won't be able to run your program. You can see that there are four using statements in your little program that are added by default. We can leave these exactly the way they are for the near future.

A Brief Introduction to Namespaces

As I just mentioned above, while discussing using statements, people, including yourself, can create huge piles or collections of code that are all related to each other. To manage these piles of code better, related code is usually put into groups called namespaces. There's a good reason for that particular name, but it is a discussion for another day.

You can see that in your program, just after the using statements, that the next thing is this:

namespace Topic01
{

In C#, the curly braces are used to start and end sections of related code called a "code block". You'll see them come up in several places as we learn C#. Every starting curly brace ('{') will have a matching ending curly brace ('}') later on, and so we see in our program that the last line of the program is the end of the namespace code block which looks like this:

}

This line of code tells us that everything in between the two curly braces belongs in the namespace "Topic01". namespace is a keyword, which is what gives the line specific meaning, but the "Topic01" part is arbitrary. You could call it anything else, and it would still work. Visual Studio used Topic01 because that was the name of your program.

The Class and Method Declarations

The next part of the code is the class and method declarations. We're going to be talking about classes and methods lots, lots more before too long, but for now, we only really need a basic understanding of them.

Here's the part I'm referring to:

    class Program
    {
        static void Main(string[] args)
        {

and then later, to close it…

        }
    }

At a basic level, a class is usually thought of as a "blueprint", or design for a particular kind of object. We'll look at this in more detail later, but most of the code you write will belong to a particular class. In this case, the name of the class is the "Program" class. We'll be making all sorts of classes as time goes along. Classes are a critical part of "object-oriented" programming languages like C# and Java.

Inside of that, you have "methods" (sometimes called functions, procedures, or subroutines in other programming languages) that is a block of code that performs a specific task. Again, we'll be talking about methods in a lot more detail later. For now, the important thing to remember is that the C# compiler is going to be looking for a method called "Main".

The rest of the stuff on that line (static, void, the parentheses ( and ), and the string[] args form what it called the "method signature" and defines certain properties about the method. These pieces are also critical for the C# compiler to find your "main" method where the program will start, so don't modify them.

We'll discuss what each of these things mean later on, in future tutorials. For now, the important thing is that you know that the C# compiler is looking for this specific line in your code to use as the starting point of your program.

Anything you put inside of the Main method will get ran by the computer, and for the next few tutorials, everything we do will be right in here.

 

Note: The command-line is a window that allows you to run commands and programs by typing the text in manually. It is often refered to as the DOS prompt, which was the operating system people used years ago, before Windows. The .NET Framework SDK, which is free, uses mostly command line tools. Therefore, I wrote this tutorial so that anyone would be able to use it. Do a search through Windows Explorer for "csc.exe", which is the C# compiler. When you know its location, add that location to your Windows path. Then open the command window by going to the Windows Start menu, selecting Run, and typing cmd.exe

The first thing you should be aware of is that C# is case-sensitive. The word "Main" is not the same as its lower case spelling, "main". They are different identifiers. If you are coming from a language that is not case sensitive, this will trip you up several times until you become accustomed to it.

The namespace declaration, using System;, indicates that you are referencing the System namespace. Namespaces contain groups of code that can be called upon by C# programs. With the using System; declaration, you are telling your program that it can reference the code in the System namespace without pre-pending the word System to every reference. I'll discuss this in more detail in Topic 06: Namespaces, which is dedicated specifically to namespaces.

The class declaration, class WelcomeCSS, contains the data and method definitions that your program uses to execute. A class is one of a few different types of elements your program can use to describe objects, such as structs, interfaces , delegates, and enums, which will be discussed in more detail in Topic 12: Structs, Topic 13: Interfaces, Topic 14: Delegates, and Topic 17: Enums, respectively. This particular class has no data, but it does have one method. This method defines the behavior of this class (or what it is capable of doing). I'll discuss classes more in Topic 07: Introduction to Classes. We'll be covering a lot of information about classes throughout this tutorial.

The one method within the WelcomeCSS class tells what this class will do when executed. The method name, Main, is reserved for the starting point of a program. Main is often called the "entry point" and if you ever receive a compiler error message saying that it can't find the entry point, it means that you tried to compile an executable program without a Main method.

A static modifier precedes the word Main, meaning that this method works in this specific class only, rather than an instance of the class. This is necessary, because when a program begins, no object instances exist. I'll tell you more about classes, objects, and instances in Topic 07: Introduction to Classes.

Every method must have a return type. In this case it is void, which means that Main does not return a value. Every method also has a parameter list following its name with zero or more parameters between parenthesis. For simplicity, we did not add parameters to Main. Later in this Topic you'll see what type of parameter the Main method can have. You'll learn more about methods in Topic 05: Methods.

The Main method specifies its behavior with the Console.WriteLine(...) statement. Console is a class in the System namespace. WriteLine(...) is a method in the Console class. We use the ".", dot, operator to separate subordinate program elements. Note that we could also write this statement as System.Console.WriteLine(...). This follows the pattern "namespace.class.method" as a fully qualified statement. Had we left out the using System declaration at the top of the program, it would have been mandatory for us to use the fully qualified form System.Console.WriteLine(...). This statement is what causes the string, "Welcome to the C# Faith Tutorial!" to print on the console screen.

Observe that comments are marked with "//". These are single line comments, meaning that they are valid until the end-of-line. If you wish to span multiple lines with a comment, begin with "/*" and end with "*/". Everything in between is part of the comment. Comments are ignored when your program compiles. They are there to document what your program does in plain English (or the native language you speak with every day).

All statements end with a ";", semi-colon. Classes and methods begin with "{", left curly brace, and end with a "}", right curly brace. Any statements within and including "{" and "}" define a block. Blocks define scope (or lifetime and visibility) of program elements.

Accepting Command-Line Input

In the previous example, you simply ran the program and it produced output. However, many programs are written to accept command-line input. This makes it easier to write automated scripts that can invoke your program and pass information to it. If you look at many of the programs, including Windows OS utilities, that you use everyday; most of them have some type of command-line interface. For example, if you type Notepad.exe MyFile.txt (assuming the file exists), then the Notepad program will open your MyFile.txt file so you can begin editing it. You can make your programs accept command-line input also, as shown in Listing 1-2, which shows a program that accepts a name from the command line and writes it to the console.

Note: When running the NamedWelcome.exe application in Listing 1-2, you must supply a command-line argument. For example, type the name of the program, followed by your name: NamedWelcome YourName. This is the purpose of Listing 1-2 - to show you how to handle command-line input. Therefore, you must provide an argument on the command-line for the program to work. If you are running Visual Studio, right-click on the project in Solution Explorer, select Properties, click the Debug tab, locate Start Options, and type YourName into Command line arguments. If you forget to to enter YourName on the command-line or enter it into the project properties, as I just explained, you will receive an exception that says "Index was outside the bounds of the array." To keep the program simple and concentrate only on the subject of handling command-line input, I didn't add exception handling. Besides, I haven't taught you how to add exception handling to your program yet - but I will. In Topic 15: Introduction to Exception Handling, you'll learn more about exceptions and how to handle them properly.

Listing 1-2. Getting Command-Line Input: NamedWelcome.cs
// Namespace Declaration
using System;

// Program start class
class NamedWelcome
{
// Main begins program execution.
static void Main(string[] args)
{
// Write to console
Console.WriteLine("Hello, {0}!", args[0]);
Console.WriteLine("Welcome to the C# Faith Tutorial!"); 
}
}

Tip: Remember to add your name to the command-line, i.e. "NamedWelcome Shabir". If you don't, your program will crash. I'll show you in Topic 15: Introduction to Exception Handling how to detect and avoid such error conditions.

If you are using an IDE, like Visual Studio, see your IDE's help documentation on how to set the command-line option via project properties. i.e. in Visual Studio 2010, double-click the Properties folder in your solution project, click the Debug tab, and add your name to Command Line Arguments. The actual step can/will differ between IDE's and versions, so please consult your IDE documentation for more information.

In Listing 1-2, you'll notice an entry in the Main method's parameter list. The parameter name is args, which you'll use to refer to the parameter later in your program. The string[] expression defines the type of parameter that args is. The string type holds characters. These characters could form a single word, or multiple words. The "[]", square brackets denote an Array, which is like a list. Therefore, the type of the args parameter, is a list of words from the command-line. Anytime you add string[] args to the parameter list of the Main method, the C# compiler emits code that parses command-line arguments and loads the command-line arguments into args. By reading args, you have access to all arguments, minus the application name, that were typed on the command-line.

You'll also notice an additional Console.WriteLine(...) statement within the Main method. The argument list within this statement is different than before. It has a forRavied string with a "{0}" parameter embedded in it. The first parameter in a forRavied string begins at number 0, the second is 1, and so on. The "{0}" parameter means that the next argument following the end quote will determine what goes in that position. Hold that thought, and now we'll look at the next argument following the end quote.

The args[0] argument refers to the first string in the args array. The first element of an Array is number 0, the second is number 1, and so on. For example, if I typed NamedWelcome Shabir on the command-line, the value of args[0] would be "Shabir". This is a little tricky because you know that you typed NamedWelcome.exe on the command-line, but C# doesn't include the executable application name in the args list - only the first parameter after the executable application.

Returning to the embedded "{0}" parameter in the forRavied string: Since args[0] is the first argument, after the forRavied string, of the Console.WriteLine() statement, its value will be placed into the first embedded parameter of the forRavied string. When this command is executed, the value of args[0], which is "Shabir" will replace "{0}" in the forRavied string. Upon execution of the command-line with "NamedWelcome Shabir", the output will be as follows:

Hello, Shabir!
Welcome to the C# Faith Tutorial!

Interacting via the Command-Line

Besides command-line input, another way to provide input to a program is via the Console. Typically, it works like this: You prompt the user for some input, they type something in and press the Enter key, and you read their input and take some action. Listing 1-3 shows how to obtain interactive input from the user.

Listing 1-3. Getting Interactive Input: InteractiveWelcome.cs
// Namespace Declaration
using System;


// Program start class
class InteractiveWelcome
{
// Main begins program execution.
public static void Main()
{
// Write to console/get input
Console.Write("What is your name?: ");
Console.Write("Hello, {0}! ", Console.ReadLine());
Console.WriteLine("Welcome to the C# Faith Tutorial!"); 
}
}

In Listing 1-3, the Main method doesn't have any parameters -- mostly because it isn't necessary this time. Notice also that I prefixed the Main method declaration with the public keyword. The public keyword means that any class outside of this one can access that class member. For Main, it doesn't Ravier because your code would never call Main, but as you go through this tutorial, you'll see how you can create classes with members that must be public so they can be used. The default access is private, which means that only members inside of the same class can access it. Keywords such as public and private are referred to as access modifiers. Topic 19: Encapsulation discusses access modifiers in more depth.

There are three statements inside of Main and the first two are different from the third. They are Console.Write(...) instead of Console.WriteLine(...). The difference is that the Console.Write(...) statement writes to the console and stops on the same line, but the Console.WriteLine(...) goes to the next line after writing to the console.

The first statement simply writes "What is your name?: " to the console.

The second statement doesn't write anything until its arguments are properly evaluated. The first argument after the forRavied string is Console.ReadLine(). This causes the program to wait for user input at the console. After the user types input, their name in this case, they must press the Enter key. The return value from this method replaces the "{0}" parameter of the forRavied string and is written to the console. This line could have also been written like this:

string name = Console.ReadLine(); Console.Write("Hello, {0}! ", name);

The last statement writes to the console as described earlier. Upon execution of the command-line with "InteractiveWelcome", the output will be as follows:

>What is your Name?  <type your name here> [Enter Key]
>Hello, <your name here>!  Welcome to the C# Faith Tutorial!

Topic 2:Operators, Types, and Variables

This Topic introduces C# operators, types, and variables. Its goal is to meet the following objectives:

  • Understand what a variable is.
  • Familiarization with C# built-in types.
  • Get an introduction to C# operators.
  • Learn how to use Arrays.

Variables and Types

"Variables" are simply storage locations for data. You can place data into them and retrieve their contents as part of a C# expression. The interpretation of the data in a variable is controlled through "Types".

C# is a "Strongly Typed" language. Thus all operations on variables are performed with consideration of what the variable's "Type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable.

The C# simple types consist of the Boolean type and three numeric types - Integrals, Floating Point, Decimal, and String. The term "Integrals", which is defined in the C# Programming Language Specification, refers to the classification of types that include sbyte, byte, short, ushort, int, uint, long, ulong, and char. More details are available in the Integral Types section later in this Topic. The term "Floating Point" refers to the float and double types, which are discussed, along with the decimal type, in more detail in the Floating Point and Decimal Types section later in this Topic. The string type represents a string of characters and is discussed in The String Type section, later in this Topic. The next section introduces the boolean type.

The Boolean Type

Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and anything else means true. However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords. Listing 2-1 shows one of many ways that boolean types can be used in a program.

Listing 2-1. Displaying Boolean Values: Boolean.cs
using System
class Booleans
{
public static void Main()
{
bool content = true;
bool noContent = false;

Console.WriteLine("It is {0} that C# Faith provides C# programming language content.", content);
Console.WriteLine("The statement above is not {0}.", noContent);
}
} 

In Listing 2-1, the boolean values are written to the console as a part of a sentence. The only legal values for the bool type are either true or false, as shown by the assignment of true to content and false to noContent. When run, this program produces the following output:

It is True that C# Faith provides C# programming language content.
The statement above is not False. 

Integral Types

In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard. For more information, visit The Unicode Home Page. table 2-1 shows the integral types, their size, and range.

Table 2-1. The Size and Range of C# Integral Types
Type Size (in bits) Range
sbyte 8 -128 to 127
byte 8 0 to 255
short 16 -32768 to 32767
ushort 16 0 to 65535
int 32 -2147483648 to 2147483647
uint 32 0 to 4294967295
long 64 -9223372036854775808 to 9223372036854775807
ulong 64 0 to 18446744073709551615
char 16 0 to 65535

Integral types are well suited for those operations involving whole number calculations. The char type is the exception, representing a single Unicode character. As you can see from the table above, you have a wide range of options to choose from, depending on your requirements.

Floating Point and Decimal Types

A C# floating point type is either a float or double. They are used any time you need to represent a real number, as defined by IEEE 754. For more information on IEEE 754, visit the IEEE Web Site. Decimal types should be used when representing financial or money values. table 2-2 shows the floating point and decimal types, their size, precision, and range.

Table 2-2. The Floating Point and Decimal Types with Size, precision, and Range
Type Size (in bits) precision Range
float 32 7 digits 1.5 x 10-45 to 3.4 x 1038
double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308
decimal 128 28-29 decimal places 1.0 x 10-28 to 7.9 x 1028

Floating point types are used when you need to perform operations requiring fractional representations. However, for financial calculations, the decimal type is the best choice because you can avoid rounding errors.

The string Type

A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string." You've seen strings being used in Topic 1, where we used the Console.WriteLine method to send output to the console.

Some characters aren't printable, but you still need to use them in strings. Therefore, C# has a special syntax where characters can be escaped to represent non-printable characters. For example, it is common to use newlines in text, which is represented by the '\n' char. The backslash, '\', represents the escape. When preceded by the escape character, the 'n' is no longer interpreted as an alphabetical character, but now represents a newline.

You may be now wondering how you could represent a backslash character in your code. We have to escape that too by typing two backslashes, as in '\\'. table 2-3 shows a list of common escape sequences.

Table 2-3. C# Character Escape Sequences
Escape Sequence Meaning
\' Single Quote
\" Double Quote
\\ Backslash
\0 Null, not the same as the C# null value
\a Bell
\b Backspace
\f form Feed
\n Newline
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab

Another useful feature of C# strings is the verbatim literal, which is a string with a @ symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as normal characters to enhance readability. To appreciate the value of verbatim literals, consider a path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes are escaped, causing the string to be less readable. You can improve the string with a verbatim literal, like this: @"c:\topdir\subdir\subdir\myapp.exe".

That is fine, but now you have the problem where quoting text is not as easy. In that case, you would specify double double quotes. For example, the string "copy \"c:\\source file name with spaces.txt\" c:\\newfilename.txt" would be written as the verbatim literal @"copy ""c:\source file name with spaces.txt"" c:\newfilename.txt".

C# Operators

Results are computed by building expressions. These expressions are built by combining variables and operators together into statements. The following table describes the allowable operators, their precedence, and associativity.

Table 2-4. Operators with their precedence and Associativity
Category (by precedence) Operator(s) Associativity
Primary x.y  f(x)  a[x]  x++  x--  new  typeof  default  checked  unchecked delegate left
Unary +  -  !  ~  ++x  --x  (T)x right
Multiplicative *  /  % left
Additive +  - left
Shift <<  >> left
Relational <  >  <=  >=  is as left
Equality ==  != right
Logical AND & left
Logical XOR ^ left
Logical OR | left
Conditional AND && left
Conditional OR || left
Null Coalescing ?? left
Ternary ?: right
Assignment =  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |=  => right

Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left, such as assignment operators where everything to the right is evaluated before the result is placed into the variable on the left.

Most operators are either unary or binary. Unary operators form expressions on a single variable, but binary operators form expressions with two variables. Listing 2-2 demonstrates how unary operators are used.

Listing 2-2. Unary Operators: Unary.cs
using System;

class Unary
{
public static void Main()
{
int unary = 0;
int preIncrement;
int preDecrement;
int postIncrement;
int postDecrement;
int positive;
int negative;
sbyte bitNot;
bool logNot;

preIncrement = ++unary;
Console.WriteLine("pre-Increment: {0}", preIncrement);

preDecrement = --unary;
Console.WriteLine("pre-Decrement: {0}", preDecrement);

postDecrement = unary--;
Console.WriteLine("Post-Decrement: {0}", postDecrement);

postIncrement = unary++;
Console.WriteLine("Post-Increment: {0}", postIncrement);

Console.WriteLine("Final Value of Unary: {0}", unary);

positive = -postIncrement;
Console.WriteLine("Positive: {0}", positive);

negative = +postIncrement;
Console.WriteLine("Negative: {0}", negative);

bitNot = 0;
bitNot = (sbyte)(~bitNot);
Console.WriteLine("Bitwise Not: {0}", bitNot);

logNot = false;
logNot = !logNot;
Console.WriteLine("Logical Not: {0}", logNot);
}
}

When evaluating expressions, post-increment (x++) and post-decrement (x--) operators return their current value and then apply the operators. However, when using pre-increment (++x) and pre-decrement (--x) operators, the operator is applied to the variable prior to returning the final value.

In Listing 2-2, the unary variable is initialized to zero. When the pre-increment (++x) operator is used, unary is incremented to 1 and the value 1 is assigned to the preIncrement variable. The pre-decrement (--x) operator turns unary back to a 0 and then assigns the value to the preDecrement variable.

When the post-decrement (x--) operator is used, the value of unary, 0, is placed into the postDecrement variable and then unary is decremented to -1. Next the post-increment (x++) operator moves the current value of unary, -1, to the postIncrement variable and then increments unary to 0.

The variable bitNot is initialized to 0 and the bitwise not (~) operator is applied. The bitwise not (~) operator flips the bits in the variable. In this case, the binary representation of 0, "00000000", was transformed into -1, "11111111".

While the (~) operator works by flipping bits, the logical negation operator (!) is a logical operator that works on bool values, changing true to false or false to true. In the case of the logNot variable in Listing 2-2, the value is initialized to false, and the next line applies the logical negation operator, (!), which returns true and reassigns the new value, true, to logNot. Essentially, it is toggling the value of the bool variable, logNot.

The setting of positive is a little tricky. At the time that it is set, the postIncrement variable is equal to -1. Applying the minus (-) operator to a negative number results in a positive number, meaning that positive will equal 1, instead of -1. The minus operator (-), which is not the same as the pre-decrement operator (--), doesn't change the value of postInc - it just applies a sign negation. The plus operator (+) doesn't affect the value of a number, assigning negative with the same value as postIncrement, -1.

Notice the expression (sbyte)(~bitNot). Any operation performed on types sbyte, byte, short, or ushort return int values. To assign the result into the bitNot variable we had to use a cast, (Type), operator, where Type is the type you wish to convert to (in this case - sbyte). The cast operator is shown as the Unary operator, (T)x, in table 2-4. Cast operators must be performed explicity when you go from a larger type to a smaller type because of the potential for lost data. Generally speaking, assigning a smaller type to a larger type is no problem, since the larger type has room to hold the entire value. Also be aware of the dangers of casting between signed and unsigned types. You want to be sure to preserve the integrity of your data. Many basic programming texts contain good descriptions of bit representations of variables and the dangers of explicit casting.

Here's the output from the Listing 2-2:

pre-Increment: 1
pre-Decrement 0
Post-Decrement: 0
Post-Increment: -1
Final Value of Unary: 0
Positive: 1
Negative: -1
Bitwise Not: -1
Logical Not: true 

In addition to unary operators, C# has binary operators that form expressions of two variables. Listing 2-3 shows how to use the binary operators.

Listing 2-3. Binary Operators: Binary.cs
using System;

class Binary
{
public static void Main()
{
int x, y, result;
float floatresult;

x = 7;
y = 5;

result = x+y;
Console.WriteLine("x+y: {0}", result);

result = x-y;
Console.WriteLine("x-y: {0}", result);

result = x*y;
Console.WriteLine("x*y: {0}", result);

result = x/y;
Console.WriteLine("x/y: {0}", result);

floatresult = (float)x/(float)y;
Console.WriteLine("x/y: {0}", floatresult);

result = x%y;
Console.WriteLine("x%y: {0}", result);

result += x;
Console.WriteLine("result+=x: {0}", result);
}
}

And here's the output:

x+y: 12
x-y: 2
x*y: 35
x/y: 1
x/y: 1.4
x%y: 2
result+=x: 9

Listing 2-3 shows several examples of binary operators. As you might expect, the results of addition (+), subtraction (-), multiplication (*), and division (/) produce the expected mathematical results.

The floatresult variable is a floating point type. We explicitly cast the integer variables x and y to calculate a floating point value.

There is also an example of the remainder(%) operator. It performs a division operation on two values and returns the remainder.

The last statement shows another form of the assignment with operation (+=) operator. Any time you use the assignment with operation operator, it is the same as applying the binary operator to both the left hand and right hand sides of the operator and putting the results into the left hand side. The example could have been written as result = result + x; and returned the same value.

The Array Type

Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size.

Listing 2-4. Array Operations: Array.cs
using System;

class Array
{
public static void Main()
{
int[] myInts = { 5, 10, 15 };
bool[][] myBools = new bool[2][];
myBools[0] = new bool[2];
myBools[1] = new bool[1];
double[,] myDoubles = new double[2, 2];
string[] myStrings = new string[3];

Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1], myInts[2]);

myBools[0][0] = true;
myBools[0][1] = false;
myBools[1][0] = true;
Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);

myDoubles[0, 0] = 3.147;
myDoubles[0, 1] = 7.157;
myDoubles[1, 1] = 2.117;
myDoubles[1, 0] = 56.00138917;
Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]);

myStrings[0] = "Shabir";
myStrings[1] = "Ravi";
myStrings[2] = "Robert";
Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]);

}
}

And here's the output:

myInts[0]: 5, myInts[1]: 10, myInts[2]: 15
myBools[0][0]: true, myBools[1][0]: true
myDoubles[0, 0]: 3.147, myDoubles[1, 0]: 56.00138917
myStrings[0]: Shabir, myStrings[1]: Ravi, myStrings[2]: Robert

Listing 2-4 shows different implementations of Arrays. The first example is the myInts Array, which is a single-dimension array. It is initialized at declaration time with explicit values.

Next is a jagged array, myBools. It is essentially an array of arrays. We needed to use the new operator to instantiate the size of the primary array and then use the new operator again for each sub-array.

The third example is a two dimensional array, myDoubles. Arrays can be multi-dimensional, with each dimension separated by a comma. It must also be instantiated with the new operator.

One of the differences between jagged arrays, myBools[][], and multi-dimension arrays, myDoubles[,], is that a multi-dimension array will allocate memory for every element of each dimension, whereas a jagged array will only allocate memory for the size of each array in each dimension that you define. Most of the time, you'll be using multi-dimension arrays, if you need multiple dimensions, and will only use jagged arrays in very special circumstances when you are able to save significant memory by explicitly specifying the sizes of the arrays in each dimension.

Finally, we have the single-dimensional array of string types, myStrings.

In each case, you can see that array elements are accessed by identifying the integer index for the item you wish to refer to. Arrays sizes can be any int type value. Their indexes begin at 0.

Summary

A variable is an identifier with a type that holds a value of that type. Simple types include the integrals, floating points, decimal, and bool. C# has several mathematical and logical operators that participate in forming expressions. C# also offers the single dimension, multi-dimension and jagged array types.

In this Topic you learned how to write simple statements and code a program that works linearly from start to finish. However, this is not as useful as it can be because you need to be able to make decisions and execute different blocks of code depending on different conditions. I invite you to return for Topic 3: Control Statements - Selection, where you can learn how to branch your logic for more powerful decision making.

Next Previous