+ All Categories
Home > Documents > C#LanguageFoundations

C#LanguageFoundations

Date post: 08-Sep-2015
Category:
Upload: shivuhc
View: 213 times
Download: 0 times
Share this document with a friend
Description:
C
35
C# Language Foundations Objectives This chapter provides a tour of various C# fundamentals which includes various ways to execute a C# program, variables, data types, conditional statements and Looping statements. At the end of this chapter delegate would be in a position to accomplish the following activities. How to Write a simple C# Program in Visual Studio IDE How to Work with C# command-line compiler, csc.exe How to work around Main How to use a variable, keyword & constant How to use Conditional statements and Loops Page 1 3 C#Language Foundations
Transcript

C# Language Foundations

3

C#Language Foundations

ObjectivesThis chapter provides a tour of various C# fundamentals which includes various ways to execute a C# program, variables, data types, conditional statements and Looping statements. At the end of this chapter delegate would be in a position to accomplish the following activities. How to Write a simple C# Program in Visual Studio IDE How to Work with C# command-line compiler, csc.exe How to work around Main How to use a variable, keyword & constant How to use Conditional statements and Loops

IntroductionC# is the latest progression in a never ending quest to make it as easy and efficient as possible for humans to program computers. Whilst it would be easy to simply describe C# as just another object oriented programming language developed by Microsoft, the fact is that C# is actually an integral part of an entire development and execution infrastructure. The origins of the C# programming syntax can be traced right back to C and C++. If you are already familiar with C or C++ then you have a big head start in terms of learning C#. C# is also accompanied by a vast framework of libraries designed to provide the programmer with readymade solutions to just about every imaginable scenario.As a C# programmer, you may choose among numerous tools to build .NET applications. Out of all available options, C# and Visual Studio IDE make lot of things easy and will provide so many great features which are listed below.1. Build an application, Fast2. Design a great looking user-interface3. Focus on solving REAL problems4. Interacting with the database.Writing a Simple C# ProgramC# is a strongly typed language, which means that every variable and objectinstance in the system is of a well-defined type. This enables the compiler to check that the operations we try to perform on variables and object instances are valid. We will learn in depth of it in the later chapters.

Well start by demonstrating a simple program and explaining its components one by one. This will introduce a range of topics, from the structure of a C# program to the method of producing program output to the screen.

In order to start writing our first C# program, do the following steps.1. Open Visual Studio IDE(Start->All Programs -> Microsoft Visual Studio 2008 -> Microsoft Visual Studio 2008)2. File -> New -> Project3. In the New Project window, under Project types select Visual C# and in the visual studio installed templates, select Console Application.4. Provide name for the Project we are creating in the Name field and set the location to store it.

Lets start by looking at a simple C# program. The complete program source is given below. The code is contained in a text file called WelcomeSAMPLE.cs

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

namespace SAMPLE{ class WelcomeSAMPLE { static void Main(string[] args) { Console.WriteLine("Welcome To SAMPLE"); } }}

When the code is compiled and executed output string Hello World will be displayed on the console.

How to Compile a Program:In Visual studio tool, Click on Build tab. In the expanded list under Build menu, click on Build ApplicationName. In the Progress bar of visual studio we can see about the status whether Build is succeeded or failed and we can check the error list if any errors are there in the Project.We can compile or build our project either by using F6 option in our key board or Ctrl + Shift + B.How to Execute a Program:In visual studio tool Click on Debug -> Start Debugging. We can also execute our project by pressing F5 option.Explanation of the Program using System tells the compiler that this program uses types from the System namespace. We will learn much about namespaces in later chapters of C#.namespace SAMPLE declares a new namespace, called SAMPLE. Any types declared within this section are members of the namespace.class WelcomeSAMPLE declares a new class type, called Program. Any members declared between the matching curly braces are members that make up this class.

static void Main(string[] args) declares a method called Main as a member of class Program. In this program, Main is the only member of the Program class. Main is a special function used by the compiler as the starting point of the program.

Console.WriteLine("Welcome To SAMPLE") line constitutes the body of Main. This statement uses a class called Console, in namespace System, to print out the message to a window on the screen.

Building C# Applications Using csc.exe

While it is true that you may never decide to build a large-scale application using the C# command line compiler(csc.exe), it is important to understand the basics of how to compile your code files by hand. There might be some scenarios we will come across executing the program from Command Prompt.

The most obvious reason is the simple fact that you might not have a copy of Visual Studio 2008. You may be in a university setting where you are prohibited from using code generation tools/IDEs in the classroom. You want to deepen your understanding of C#.

To illustrate how to build a .NET application IDE-free, we will build a simple executable assembly named WelcomeSAMPLE.exe using the C# command-line compiler and Notepad.

Open Notepad (using the Start -> Programs -> Accessories menu option) and enter thefollowing trivial C# code:

using System;namespace SAMPLE{ class WelcomeSAMPLE { static void Main(string[] args) { Console.WriteLine("Welcome To SAMPLE"); } }}

Once you have finished, save the file in a convenient location with name WelcomeSAMPLE.cs. To compile and execute the program do the following way.1. Start -> All Programs ->Microsoft Visual Studio 2008 -> Visual studio tools -> visual studio 2008 command prompt2. Navigate to the path where Project is stored.3. Type the following command in the VS2008 command prompt to compile the project.

CSC WelcomeSAMPLE.cs

The above step will generate an exe file with the name WelcomeSAMPLE.exe.

4. Type WelcomeSAMPLE in VS2008 command prompt or double click the exe file to get the output of the program.

To get the help relating to commands available with command line compiler type CSC -?

/out : This option is used to specify the name of the assembly to be created. Bydefault, the assembly name is the same as the name of the initial input *.cs file.

/target:exe This option builds an executable console application. This is the defaultassembly output type, and thus may be omitted when building this type of application.

/target:library This option builds a single-file *.dll assembly.

Referencing External Assemblies:We can refer external assemblies in our program by writing that assembly name with keyword using.using System;using System.Windows.Forms;

class SimpleProgram { static void Main() { Console.WriteLine("Testing! 1, 2, 3"); // Add this! MessageBox.Show("Hello..."); } }

You must inform csc.exe about the assembly that contains the namespaces you are using. Given that you have made use of the System.Windows.Forms.MessageBox class, you must specify the System.Windows.Forms.dll assembly using the /reference flag (which can be abbreviated to /r) as shown below.

csc /r:System.Windows.Forms.dll SimpleProgram.cs

Investigating Main()By default, Visual Studio 2008 names the class containing Main() method as Program; however, you are free to change this if you so choose. Every executable C# application must contain a class defining a Main() method, which is used to signify the entry point of the application.Formally speaking, the class that defines the Main() method is termed the application object. While it is possible for a single executable application to have more than one application object, you must inform the compiler which Main() method should be used as the entry point via the /main option of the csc.exe.Variations on the Main() MethodBy default, Visual Studio 2008 will generate a Main()method that has a void return value and an array of string types as the single input parameter. However this is not the only possible form of Main(). It is permissible to construct your applications entry point using any of the following signatures. // void return type, array of strings as the argument.static void Main(string[] args){}// int return type, array of strings as the argument.static int Main(string[] args){}// No return type, no arguments.static void Main(){}// int return type, no arguments.static int Main(){}Obviously, your choice of how to construct Main() will be based on two questions. First, do you want to return a value to the system when Main() has completed and your program terminates? If so, you need to return an int data type rather than void. Second, do you need to process any user supplied command-line parameters? If so, they will be stored in the array of strings. Lets examine all of our options.Processing Command-Line ArgumentsIn the real world, an end user supplies the command-line arguments used by a given application when starting the program. Now that you better understand the return value of the Main() method, lets examine the incoming array of string data. Assume that you now wish to update your application to process any possible command-line parameters. One way to do so is using a C# for loop (do note that C#s iteration constructs will be examined in some detail near the end of this chapter):for(int i = 0; i < args.Length; i++) {Console.WriteLine("Arg: {0}", args[i]);}Console.ReadLine();

We can pass command line arguments either from command prompt when compiling the program using CSC or we can pass from Visual Studio IDE. If we are executing the program from command line compiler pass the arguments as shown below. ProgramName.exe List of arguments separated by White Space.If we are executing the program from IDE, double-click the Properties icon from Solution Explorer and select the Debug tab on the left side. From here, specify values using the Command line arguments text box.

Basic Input and Output with the Console ClassThe Console type defines a set of methods to capture input and output, all of which are static and are therefore called by prefixing the name of the class (Console) to the method name. As you have seen, WriteLine() pumps a text string (including a carriage return) to the output stream. The Write() method pumps text to the output stream without a carriage return. ReadLine() allows you to receive information from the input stream up until the Enter key is pressed, while Read() is used to capture a single character from the input stream. The first parameter to WriteLine() represents a string literal that contains optional placeholders designated by {0}, {1}, {2}, and so forth. Be very aware that the first ordinal number of a curly-bracket placeholder always begins with 0. The remaining parameters to WriteLine() are simply the values to be inserted into the respective placeholders.Console.WriteLine("{0}, Number {0}, Number {0}", 9);Console.WriteLine("{1}, {0}, {2}", 10, 20, 30);Multiple Main Methods:As we discussed in the earlier sections in a program more than one Main() is allowed. If we have more than one Main method, to execute the program use the following command. Csc filename.cs /main:classname

VariablesVariables are values that can change as much as needed during the execution of a program. One reason you need variables in a program is to hold the results of a calculation. Hence, variables are locations in memory in which values can be stored. Every variable has a type that determines the values to be stored in the variable. C# is a type-safe language and the C# compiler guarantees that values stored in variables are always of the appropriate data type.Variable DeclarationsIn C# all variables must be declared before they are used. In the declaration you must specify a data type and a name for the variable so that memory can be set aside for the variable. Syntax Datatype variable-name[=default value];Example: int x = 10; String MyName;Rules for Variable Naming:1. Variable name can be any length.2. Except underscore, special characters are not allowed3. First Letter must not begin with a digit

Scope of Variable The scope of a variable is the region of code from which the variable can be accessed. In general, the scope is determined by the following rules: A field (also known as a member variable) of a class is in scope for as long as its containing class is in scope (this is the same as for C++, Java, and VB). A local variable is in scope until a closing brace indicates the end of the block statement or method in which it was declared. A local variable that is declared in a for, while, or similar statement is in scope in the body of that loop. Does Scope clashes for Fields and Local Variables? NOclass progam{ int j = 10; public static void Main(String[] args) { int j = 20; Console.WriteLine(j); }}

ConstantsPrefixing a variable with the const keyword when it is declared and initialized designates that variable as a constant. As the name implies, a constant is a variable whose value cannot be changed throughout its lifetime:const int a=100; // This value cannot be changed.Characteristics of Constants They must be initialized when they are declared, and once a value has been assigned, it can never be overwritten. The value of a constant must be computable at compile time. Constants are always implicitly static. Advantages of Constants Constants make your programs easier to read by replacing magic numbers and strings with readable names whose values are easy to understand. Constants make your programs easier to modify Constants make it easier to avoid mistakes in your programsData types:Every Variable in C# is associated with a data type. Data types specify the size and type of value that can be stored. C# is very rich in its data types.The types in C# are primarily divided into three categories:1. value types2. Reference types3. Pointers

Value types and reference types differ in two characteristics:1. where they are stored in the memory2. How they behave in the context of assignment statements

Value types are going to be stored on the stack, and when a value of a variable is assigned to another variable, the value is actually copied. This means that two identical copies of the values are available in memory. Reference types are stored in the heap, and when an assignment between two variables occurs, actual value reference is copied and there are two references for a single variable. The third category is pointers, which is available for unsafe code.VALUE Types:Value types of C# can be grouped into two categories.1. User-defined types2. predefined types

User-defined types include the data types int, float, double, char, bool and so on.Syntax: datatype VariableName;Example: int MyNumber; float Interest;We can define our own complex types known as user-defined value types which includes struct types and enumerations which we will be discussing later.Reference Types:Reference types are also two types.1. User-defined types2. predefined types

Predefined types include string and object.Example: string MyName; Object Name;User-defined types include 1. classes2. interfaces3. delegates4. arrays

Boxing: Converting the value type to reference type is known as boxing. In Conversion process, variable memory location is also changed from stack to the heap When the compiler finds a value type where it needs a reference type, it creates an object box into which it places the value of the value types.

int m = 20; object om = m; // creates a box to hold m int m = 20; object om = m; m=20; Console.WriteLine(m); Console.WriteLine(om);

UnBoxing: Converting the reference type to value type is known as unboxing. In Conversion process, variable memory location is also changed from heap to the stack Unboxing is an explicit conversion processE.g. Object o = 5; int i = (int)o;When unboxing a value, we have to ensure that the value type is large enough to hold the value of the object. Otherwise runtime error may occur.Differences between stack and Heap:The stack is used to allocate temporary objects while the heap is used by a programmer to reserve allocation. Basically, an object in a heap is not scope dependent; it dies when you tell it to. Meanwhile, an object on the stack is destroyed automatically when its scope ends. The stack is used to allocate temporary objects while the heap is used by a programmer to reserve allocation. There are two places the .NET framework stores items in memory as your code executes. If you haven't already met, let me introduce you to the Stack and the Heap. Both the stack and heap help us run our code. They reside in the operating memory on our machine and contain the pieces of information we need to make it all happen.

Operators:C# provides a large set of operators, which are symbols that specify which operations to perform in an expression. Operations on integral types such as ==, !=, , =, binary +, binary -, ^, &, |, ~, ++, --, and sizeof() are generally allowed on enumerations. In addition, many operators can be overloaded by the user, thus changing their meaning when applied to a user-defined type. The following table gives the list of operators available in C#.CategoryOperator (s)

Arithmetic+ , - , * , / , %

Logical&& , || , !

String Concatenation+

Increment & Decrement++ , - -

Bit Shifting>

Comparison< , > , = , == , !=

Assignment=

Short Hand Assignment+=, -=, *=, /= etc

Member Access.

Indexing[]

Cast()

Ternary Operator?:

class Program { static void Main(string[] args) { int x = 5, y; y = x++; Console.WriteLine("y: {0}, x: {1}", y, x); x = 5; y = ++x; Console.WriteLine("y: {0}, x: {1}", y, x); x = 5; y = x--; Console.WriteLine("y: {0}, x: {1}", y, x); x = 5; y = --x; Console.WriteLine("y: {0}, x: {1}", y, x); } }

Short-Circuit Operatorclass Program { static void Main(string[] args) { int n, d; n = 10; d = 2; if (d != 0 && (n % d) == 0) Console.WriteLine(d + " is a factor of " + n); d = 0; // now, set d to zero Console.WriteLine("Since d is zero, the second operand is not evaluated."); if (d != 0 && (n % d) == 0) Console.WriteLine(d + " is a factor of " + n); Console.WriteLine("try the same thing without short-circuit operator. This will cause a divide-by-zero error."); if (d != 0 & (n % d) == 0) Console.WriteLine(d + " is a factor of " + n); } }

Left Shift & Right Shift Operatorsclass Program { static void Main(string[] args) { int n; n = 10; Console.WriteLine("Value of n: " + n); Console.WriteLine("multiply by 2"); n = n 1; Console.WriteLine("Value of n after n = n / 2: " + n); Console.WriteLine("divide by 4"); n = n >> 2; Console.WriteLine("Value of n after n = n / 4: " + n); Console.WriteLine(); Console.WriteLine("reset n"); n = 10; Console.WriteLine("Value of n: " + n); Console.WriteLine("multiply by 2, 30 times"); n = n


Recommended