Introduction to C#



Introduction to C#

A computer needs a set of instructions called a program to perform any operation. A program needs to be written in a specific language called programming language, so that the computer can understand the instructions. C# is one such programming language.
This chapter introduces you to C#. it explains how to define classes and declare variables in C#. In addition, it discusses how to create the object of a class. Further, it discusses how to write execute C# programs.
Introducing C#

Computer languages have come a long way since the 1940s.during that period, scientists punched instructions into large, room-sized computer systems. These instructions were given in machine language, which consisted of a long series of zeroes and ones. These machine instructions were executed directly by the CPU. The machine language is called the first generation of computer language, the assembly language. Assembly language is easier to write than machine could still understand only machine language. Therefore, the assembler software was developed to translate the code written in assembly language into machine language.
In 1967, martin Richard developed a language called BPCL for writing operating systems. An operating system is a set of program that manages the resources of a computer and its interactions with users. The era of the third generation of computer language had arrived. In 1970, ken Thompson teamed up with Dennis Ritchie and wrote an initial version of the Unix operating system for a DEC PDP-7 computer.
Dennis Richie was working on a project to further develop the UNIX operating system. He wanted a low level language, like the assembly language, that could control hardware efficiently. At the same time, he wanted the language to provide the features of a high-level language, that is, it should be able to run on different types of hardware.
B had performance drawbacks, so in 1972 he rewrote B and called it C. Therefore, C is categorized as both a second and a third generation language. Thompson and Ritchie rewrote the UNIX operating system in C. in the years that followed; C was widely accepted and used over different hardware platforms. This led to many variations of C. in 1989, the American national standards institute (ANSI), along with the international standards organization (ISO), approved a machine-independent and standard version of C.
In the early 1980s, Bjarne Stroustrup up of bell labs developed the C++ language. In his own words,” C++ was designed primarily so that my friends and I would not have to program in assembly, C, or various modern high-level languages. Its main purpose was to make writing good programs easier and more pleasant for the individual programmer.”
C++ was originally known as ‘C with classes’ because two languages contributed to its design: C, which provided low-level features, and simula67, which provided the class concept. C++ is an object-oriented language. Other object-oriented language are java, Smalltalk, and C# (pronounced as C sharp).
Introducing compilers
All language Have a vocabulary, which is a list of words that have a specific meaning in that language. Language Also have grammar rules, which state the rules for combining words to form sentences. This ensures that whatever is spoken in a particular language is understood in the same way by all people who know the language. Similarly, programming language also have a vocabulary, which is referred to as of keywords of that language, and a grammar, which is referred to as the syntax.
Consider a scenario, where one person speaks in English with the other person. However, the person who is listening understands Chinese and not English. Therefore, he calls a translator who can translate the words of English to Chinese. Similarly, computers cannot directly understand the instructions written in a programming language. Therefore, you need a translator to convert the instructions written in a programming language to machine language.
A computer is a special that program that processes the statements written in a particular programming language and converts them into machine language. Lake everything else in the computer, the compiler also follows the input-process-output (I-O-P) cycle. It takes the programming language instructions to convert them to machine language. These instructions can then be executed by the computer. This process of conversion is called compilation.
The following figure shows the working of a compiler.
 program written
Compiler for language 2
Compiler for language 1
  in language 1                                                                                                                    machine language program 1

program written in language 2
                                                                                                                                               machine language program 2




Working of a compiler
For each programming language, there is a different compiler available. For example, to compile a program written in the C language, you require a C compiler. For a java program, you require a Java Compiler. For C# program, you will use the CSC compiler.
Which question
A                      is a special program that converts a particular
Programming language into machine language.


                 compiler



Using C# for writing programs
Similar to the various programming language, C# also has some predefined keywords that can be used for writing programs. For example, class is a keyword in C# that is used to define classes. Keywords are reserved words that have a special meaning. Further, the syntax for C# defines rules for grammatical arrangement of these keywords. For example, the syntax of declaring a class in C# is:
Class<class name>
{
………………
}
In the preceding syntax, the braces, known as delimiters, are used to indicate the start and end of a class body.
Classes in C#
C# classes are the primary building blocks of the language. C# also provides certain predefined set of classes and methods. These classes and methods provide various basic functionalities that you may way to implement in your application.
For example, if you want to perform some input/output operations in your application, you can use predefined classes available in the system. Io  namespace
In addition to using the predefined classes, consider the following code,
Which defines a classes named Hello:
Public class hello
{
Public static void Main(string [] args)
{
   System. Console. Write Line (Hello, World!\n”);
}
}
The preceding class declaration includes the method, main() that will display the message. “Hello, World!” on your screen. The preceding code includes the following components:
The class keyword
The class keyword is used to declare a class. In the preceding code, the class keyword declares the class, Hello.
The class name
The class keyword is following by the name of the class. In the preceding code, Hello is the name of the class defined by using the class keyword.
Class naming conventions in C#
Class name should follow certain naming conventions or guidelines. A class name:
           Should be meaningful (strongly recommended).
          Should ideally be a noun.
            Can use either the Pascal case or Camel case. In Pascal case, the first letter is capitalized and the rest of the letters are in lower case, such as My class. In camel case, the first letter is in lower case and the first letter of each subsequent word is capitalized, such as my class or int Employee Details.
Rules for naming classes in C#
In addition to the conventions, there are certain rules that must be following while naming classes in C#. The name of classes:
Ø  Must begin with a letter. This letter may be followed by a sequence of letters, digits (0-9), or ‘
Ø  ‘_’. The first character in a class name cannot be a digit.
Ø  Must not contain an embedded space or a symbol like? -+!@#%^&*()[]{}.,;:”’/and \. However,              an underscore (‘_’) can be used wherever a space is required.
Ø  Must not use a keyword for a class name. For example, you cannot declare a class called public.
           
The main () method
1.       The first line of code that a C# compiler looks for in the source file is the main () method. This method is the entry point for an application. This means that the execution of code starts from the main () method.
2.       The main () method is ideally used to create objects and invoke the methods of various classes that constitute the program.
The System. Console. WriteLine ()
Console is a class that belongs to the system namespace. The console class includes a predefined Write Line () method. This method display the enclosed text on the user’s screen. The console class has various other method that are used for various input/output operations.
The dot character (.) is used to access the Write Line () method, which is present in the console class of the System namespace.
The System. Write Line () statement can also be written as Console. Write Line () if the statement, using System is included as the first line of the code.
The  following code snippet is an example of the console. Write Line () method:
Console. Write Line(“Hello, world! \n”);
The preceding code snippet will display the following message on the screen:
Hello, World! 
Escape sequences
To display special characters, such as the new line character or the backspace character, you need to include appropriate escape sequences in your code. An escape sequence is a combination of characters consisting of a backslash (\) followed by a letter or a combination of digits.
The following table lists some of the escape sequences provided in C#.
Escape sequence
Sequence description
\’
Single quotation mark
\”
Double quotation mark
\\
Backslash
\0
NULL
\a
Alert
\b
Backspace
\n
New line
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
The common escape sequences in C#
The following code snippet depicts the usage of the new line escape sequence:
Console. Write Line (“Hello  \n World”);
The preceding code snippet will display the following message on the screen:
Hello
World
Which question 
Identify the output of the following code snippet:
Console. Write Line (“Dr\b\b tom Wilkins”);
        Dr\b\b tom Wilkins
        Dr tom Wilkins
        Tom Wilkins
        Dr\b tom Wilkins
 This ans =(Tom Wilkins)


Using variables  
User
5,3


Num1
5
Num2
3


Memory allocated
Consider a situation where you have to create a program that accepts two numbers from a urea and display the sum of the numbers on the screen. New, while reading the numbers provided by the user, you need to store these numbers somewhere in the memory so that you can perform the add operation on the numbers. You can store the numbers in the memory by storing user input in the memory by using variables.

Using variables to store user input
In the preceding figure, a user provides 5 and 3 as input. The digit 3 is stored in a variable, num2. A variable is a location the value. The value could be an integer, such as ‘L’. A variable is associated with a data type that defines the type of data that can be stored in the variable.
For example, a variable called tennis player name will ideally store Characters, whereas a variable called High score will store numbers. A program refers to a variable by its name.
For example, a variable called Tennis Player Name will ideally store characters, whereas a variable called High_ Score will store number. A program refers to a variable by name.

The if ….. construct
The if statement in the if ……. Else conditional construct is followed by a logical expression where data is compared and a decision is made on the basis of the result of the comparison. The following statements depict the syntax for the if ……. Else construct:
If (expression)
{
Statements;
}
Else
{
Statements;
}
Consider an example where you have to decide if you want to have dinner or you want to go to sleep. The condition on which you make a decision will be your hunger. If you are, you will have dinner; else you will go to sleep.
The following code snippet shows the decision making of the preceding example by using the if ….. else construct:
If (hungry==true)
{
Console.WriteLine(“Go and have Dinner!”);
]
Else
{
Console.WriteLine (“ Go to sleep”);
}
The following code shows the use of the if …. Else construct:
Using System;
Namespace video
{
Class Game
{
Int Age;
Console.WriteLine(“Enter your Age:”);
Age = convert.ToInt32(console.ReadLine());
If (Age<12)
{
Console.WriteLine(“Sorry! This game is for children above 11 years.”);
}
else
{
Console.WriteLine(“play the Game.”);
}
}
}
The preceding code checkswhether the age of the player is less than 12. The condition in the if statement checks the player, and if the condition is true, the statements in the else block are executed.
The output of the preceding code will be:
Enter your Age:
14
Play the Game
The else block in the if ……else construct is optional and can be omitted. The following code snippet shows an example of an if …….. else construct without the else block:
Int var = 5;
If (var>0)
Console.WriteLine(“var is a positive number.”);
The if …. Else constructs can also be nested inside each other:
Consider an example where you want to buy a specific model of Nike shoes. You go to a shoe shop and ask the shopkeeper if shoes of Nike brand are available. If they have the shoes, you will ask for the model number that you are looking for. If the requested shoe model is available with them, then you will buy the shoes; else, you will leave the shop. Therefore, in this situation you have to make two decisions one after the other. You can take successive decisions in your program by using the nested if …… else construct.
The following code snippet shows the implementation of the preceding example by using the nested if ……. Else construct:
If (Nike==available)
If (Mode==M007)
Console.WriteLine(“Buy shoe!”);
Else
Console.WriteLine(“Leave the shop!”);
The following code snippet shows the use of a nested if ………. Else construct:
Int Number1, Number2, Number3;
Number1 = 10;
Number2 = 20;
Number3 = 30;
If (Number1 > Number2)
{
If (Number1> Number3)
Console.WriteLine(“Number1 is the greatest. ”);
Else
Console.WriteLine(“Number3 is the greatest. ”);
}
Else
{
If (Number2 > Number3)
Console.WriteLine(“Number2 is the greatest.”);
Else
Console.WriteLine(“Number3 is the greatest.”);
}
The preceding code snippet display the greatest of the three numbers, Number1, Number2, Number3.
The nested if ……. Else construct can be represented by using logical operators.
The preceding example of the Nike shoe can be changed to an if ……… else construct by using logical operators. The following code snippet shows the converting of the nested if …….. else construct to an if ……. Else construct by using logical operators:
If ((Nike==available)&& (Model==M007))
Console.WriteLine(“Buy shoe!”);
Else
Console.WriteLine(“Leave the shop!”);
The following code snippet shows the use of an if …………else construct by using logical operators:
Int Number1, Number2, Number3;
Number1 = 10;
Number2 = 20;
Number3 = 30;
If ((Number1> Number2) && (Number2 > Number3))
Console.WriteLine(“Number1 is the greatest”);
In the preceding code snippet, the Console.WriteLine(“Number1 is the greatest”); statement is executed only if both the conditions around the && operators evaluate to true.
The switch….case Construct
Another conditional construct available in C# is the switch …….. case construct:
Switch (VariableName)
{
Case constantExpression_1:
         Statements;
Break;
case Constantexpression_2:
         statements;
break;
………….
Case ConstantExpression_n:
        Statements;
Break;
Default:
Statements;
Break;
}
When the switch statements is executed, the variable given in the switch statements is evaluated and compared with each case constant. If one of the constants is equal to the value of the variable given in the switch statements, control is passed to the statements following the matched case statements. The break statements is used to exit the switch statements. This prevents the execution of the remaining case statements by ending the execution of the switch ……….. case construct. If none of the cases match, the statements under the default statements are executed.
The keyword switch following by variable in parentheses, as shown in the following code snippet:
Switch (var)
Each case keyword is followed by a possible value for the variable, as shown in the following statement:
Case constantValue:
The data type of the constant should match the data type of the variable being evaluated by the switch construct. Before entering the switch construct, a value should be assigned to the switch variable.
You can replace a complex if ………. Else construct with the switch ……. Case construct when you want to check multiple values for a variable. The following code snippet is an example of the nested if ……… else construct:
Int Grade;
Grade = 3;
If (Grade == 1)
Console.WriteLine(“OK”);
Else if (Grade == 2)
Console.WriteLine(“Good”);
Else if (Grade == 3)
Console.WriteLine(“Excellent”);
Else
Console.WriteLine(“Invalid value of Grade”);
The preceding code can be replaced by a simple switch ……. Case construct, as shown in the following code snippet:
Int Grade;
Grade = 500;
Switch (Grade)
{
Case 1:
Console.WriteLine(“OK”);
Break;
Console.WriteLine(“Good”);
Case 3:
Console.WriteLine(“Excellent”);
Break;
Default:
Console.WriteLine(“Invalid value of Grade”);
Break;
}
The switch …….. case construct evaluates an expression only once at the top of the structure, whereas the if ……… else construct evaluates the expression for each if statement.




2 comments: