Chapter 1: C# - Basic Syntax
Total Page:16
File Type:pdf, Size:1020Kb
1 CHAPTER 1: C# - BASIC SYNTAX Contents 1.0 Review of .NET Framework 1.1 Introduction to C# 1.2 Variables and Expressions 1.2.1 Identifier 1.2.2 Variable 1.2.3 Keyword 1.2.4 Data Type 1.2.5 Primitive Type 1.2.6 Literals 1.2.7Operators 1.2.8 Type Casting 1.2.9 Boxing and Unboxing 1.2.10 Arrays 1.2.11Expressions 1.2.12 Statements 1.2.13 Comments 1.3Flow Control Structures 1.3.1 Selection Statements 1.3.2 Repetition Statements 1.3.3Break and Continue Statements 1.4Functions 1.5 Debugging and Error Handling 1.6 Example Programs 1.7 Summary 1.8 Exercise Reference 1 2 1.0 Review of .NET Frameworks The .NET Framework is a development platform for building apps for web, Windows, Windows Phone, Windows Server, and Microsoft Azure. The .NET Framework is a managed execution environment for Windows that provides a variety of services to its running apps. It consists of two major components: the common language runtime (CLR), which is the execution engine that handles running apps, and the .NET Framework Class Library, which provides a library of tested, reusable code that developers can call from their own apps. The services that the .NET Framework provides to running apps include the following: 1) Memory management. In .NET Framework apps, the CLR allocates and releases memory and for handling object lifetimes on behalf of the app. 2) A common type system. In the .NET Framework, basic types are defined by the .NET Framework type system and are common to all languages that target the .NET Framework. 3) An extensive class library. Instead of having to write vast amounts of code to handle common low-level programming operations, programmers use a readily accessible library of types and their members from the .NET Framework Class Library. 4) Development frameworks and technologies. The .NET Framework includes libraries for specific areas of app development, such as ASP.NET for web apps, ADO.NET for data 2 3 access, Windows Communication Foundation for service-oriented apps, and Windows Presentation Foundation for Windows desktop apps. 5) Language interoperability. Language compilers that target the .NET Framework emit an intermediate code named Common Intermediate Language (CIL), which, in turn, is compiled at runtime by the common language runtime. With this feature, routines written in one language are accessible to other languages, and programmers focus on creating apps in their preferred languages. 6) Version compatibility. With rare exceptions, apps that are developed by using a particular version of the .NET Framework run without modification on a later version. 7) Side-by-side execution. The .NET Framework helps resolve version conflicts by allowing multiple versions of the common language runtime to exist on the same computer and an app can run on the version of the .NET Framework with which it was built. 8) Multitargeting. By targeting .NET Standard, developers create class libraries that work on multiple .NET Framework platforms supported by that version of the standard. 1.1 Introduction to C# C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. You can use C# to create Windows client applications, XML Web services, distributed components, client-server applications, database applications, etc. The syntax of C# is 70% Java, 10% C++, 5% Visual Basic, 15% new.C# provides powerful features such as nullable value types, enumerations, delegates, lambda expressions and direct memory access. C# supports generic methods and types, collection classes having enumerators and iterators that are simple to use by client code. C# supports the object-oriented programming concepts of encapsulation, inheritance, and polymorphism. All variables and methods are encapsulated within class definitions. A class may inherit directly from one parent class, but it may implement any number of interfaces. It supports method overloading and method overriding. In C#, a struct is like a lightweight class; it is a stack-allocated type that can implement interfaces but does not support inheritance. In addition to these basic object-oriented principles, it has several innovative language constructs, including the following:Encapsulated method signatures called delegates, which enable type-safe event notifications.Properties, which serve as acessors for private member variables.Attributes, which provide declarative metadata about types at run time.Language- Integrated Query (LINQ) which provides built-in query capabilities across a variety of data sources. 3 4 1.2 Variables and Expressions 1.2.1 Identifier An identifier, in C#, is the user-defined name of a program element. It can be a namespace, class, method, variable or interface. Identifiers are symbols used to uniquely identify a programelement in the code. They are also used to refer to types, constants, macros and parameters. The identifier can begin with either a letter (uppercase or lowercase) or a underscore ('-') or the symbol '@'. The succeeding characters can be any letter or digit or '-'. May contain Unicode escape sequences (e.g. \u03c0 for p). 1.2.2 Variable The variable is a name given to a data value. A variable holds the value of specific type e.g string, int, etc. A variable can be declared and initialized later or declared & initialized at the same time. The value of a variable can be changed at any time throughout the program as long as it is accessible.Examples: someName, sum_of3, _10percent, @while, \u03c0. 1.2.3 Keyword Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. There are 77 keywords. Some of them are: is, base, checked, decimal, delegate, event,explicit,extern,fixed,foreach, implicitininternal, is,lock,object,override,params,readonly,ref,sealed,stackalloc, unchecked,unsafe,using. 1.2.4 Data Type C# contains two general categories of built-in data types: value types and reference types. 4 5 All types are compatible with object - can be assigned to variables of type object -all operations of type object are applicable to them Difference between Value Type and Reference Type Variable of ... Value Types Reference Types contains value reference stored on stack (or in an object) heap initialization 0, false, '\0' null assignment copies the value copies the reference example inti = 17; string s = "Hello"; int j = i; string s1 = s; 1.2.5 Primitive Type Primitive Types are non-numeric and numeric. The non-numeric are bool and char. The former represents the values true/false. The latter is 16-bit quantity to hold a Unicode character, which defines the character set for all languages of the world. long form range sbyte System.SByte -128 .. 127 byte System.Byte 0 .. 255 short System.Int16 -32768 .. 32767 ushort System.UInt16 0 .. 65535 31 31 int System.Int32 -2 .. 2 -1 32 uint System.UInt32 0 .. 2 -1 63 63 long System.Int64 -2 .. 2 -1 64 ulong System.UInt64 0 .. 2 -1 float System.Single 1.5E-45 .. 3.4E38 (32 Bit) double System.Double 5E-324 .. 1.7E308 (64 Bit) decimal System.Decimal 1E-28 .. 7.9E28 (128 Bit) bool System.Boolean true, false char System.Char Unicode character 5 6 The numeric type are integral types to represent integral decimal, octal and hexadecimal values; and the floating types to represent floating point values. The decimal is a floating type for financial calculations having higher precision. It provides 28-29 significant digits. 1.2.6 Literals The Literals are fixed values in human readable form. The bool literals are true or false. The char literals are enclosed by single quotation marks. E.g. „a‟, „3‟, „&‟. They can also be represented by their Unicode hexadecimal value. E.g. \0x0041 is „a‟; \0x0391 is Greek letter „α‟. The string literal is enclosed within double quotes. E.g. “C”, “Hello World”, “1234”. Integer literals are specified as number. E.g. 10, -100 are decimal integers. 045 is an octal integer. 0xCD87 and 0x ffb6 are hexadecimal integers. Examples of floating point literals are 1.23, 4.5e20, 7.78E-12. The decimal literal is specified by appending a „m‟ or „M‟ at the end. E.g. 5.3445m, 7.123345M. When a char literal begins with the symbol „\‟ (called as escape sequence then the letter which follows it has special meaning. E.g. „\n‟ indicates a new line; „\t‟ is a horizontal tab; „\\‟ is a backslash; „\”‟ is a double quote. Integer literals, the type of the integer literal is the smallest integer type that will holdit, beginning with int. Thus, an integer literal is either of type int, uint, long, or ulong,depending upon its value. Floating-point literals are of type double. If you do not want the C#‟s default type for a literal, you can explicitly specify its type by including a suffix. To specify a long literal, append an l or an L. E.g. 25L is a long.To specify an unsigned integer value, append a u or U. E.g. 513U is a uint. To specify an unsigned, long integer, use ul or UL. E.g.1234789UL is of type ulong. To specify a float literal, append an F or f to the constant. E.g. 10.19F is of type float. 1.2.7 Operators C# has a rich set of operatorswhich allows the programmer to construct varied types of expressions. Most of them are similar to those found in C++ and other modern languages. They can be categorized in various groups: Arithmetic, relational, logical, bitwise, shift, assignment, compound assignment, etc. There are other operators which handle specialized 6 7 situations, like indexing an array, accessing the members of class, etc.Operator precedence is a set of rules which defines how an expression is evaluated.But if both the operators have same precedence, then the expression is evaluated based on the associativity of operator (left to right or right to left).