210
1) Overview of C# : Programming structure of C# , editing, compiling & executing C# programs, namespace, comments, using aliases for namespace classes, using command line argument, maths function. 2) Literals , variables & data types : literals, variables, data types, value types, reference type, declaration of variables, initialization of variables, default values, constant variables, scope of variables, boxing & unboxing. 5) Operators & expressions : arithmetic operators, relational operators, logical operators, assignment operators, increment & decrement operators, conditional operator, Bitwise operators, special operators, arithmetic expressions, evaluation of expressions, precedence of arithmetic operators , type conversions, operator precedence & associativity, mathematical functions. 6) Decision making & branching : if statement, if …else statement, nesting of if… else statement, the else if ladder, switch statement, the ?: operator. 7) Decision making & looping : while statement, do statement, for statement, foreach statement, jumps in loops. 8) Methods in C# : declaring methods, the main method, invoking methods, nesting of methods, method parameters, pass by value, pass by reference, the output parameters, variable arguments list, method overloading. 9) Arrays : 1-D array, creating an array, 2-D arrays, variable size arrays, the system. array class, ArrayList class. 10) String Handling: Creating strings, strings methods, inserting strings using systems, comparing strings, finding substrings, mutable strings, arrays of strings, regular expressions. 11) Structures & enumeration : structures, structs with methods, nested structs, differences between classes & structs, enumerations, enumerator initialization, enumerator ____________________________________________________________ ____ C # Notes Prepared By Prof: Agi Thomas 1

c Sharp Notes

Embed Size (px)

Citation preview

1) Overview of C# : Programming structure of C# , editing, compiling & executingC# programs, namespace, comments, using aliases for namespace classes, using command line argument, maths function. 2) Literals , variables & data types : literals, variables, data types, value types, reference type, declaration of variables, initialization of variables, default values, constant variables, scope of variables, boxing & unboxing. 5) Operators & expressions : arithmetic operators, relational operators, logical operators, assignment operators, increment & decrement operators, conditional operator, Bitwise operators, special operators, arithmetic expressions, evaluation of expressions, precedence of arithmetic operators , type conversions, operator precedence & associativity, mathematical functions. 6) Decision making & branching : if statement, if else statement, nesting of if else statement, the else if ladder, switch statement, the ?: operator. 7) Decision making & looping : while statement, do statement, for statement, foreach statement, jumps in loops. 8) Methods in C# : declaring methods, the main method, invoking methods, nesting of methods, method parameters, pass by value, pass by reference, the output parameters, variable arguments list, method overloading. 9) Arrays : 1-D array, creating an array, 2-D arrays, variable size arrays, the system. array class, ArrayList class. 10) String Handling: Creating strings, strings methods, inserting strings using systems, comparing strings, finding substrings, mutable strings, arrays of strings, regular expressions. 11) Structures & enumeration : structures, structs with methods, nested structs, differences between classes & structs, enumerations, enumerator initialization, enumerator base types, enumerator type conversion, common programming errors. 12) Classes & objects: Basic principles of OOPs , class, objects, constructors, static members, static constructors, private constructors, copy constructors, destructors, member initialization, the this reference, nesting of classes, constant members, read only members, properties, indexers. 13) Inheritance & polymorphism : classical inheritance, containment inheritance, defining a subclass, visibility control, defining subclass constructors, multilevel inheritance, hierarchical inheritance, overriding methods, hiding methods, abstract classes, abstract methods, sealed classes: Preventing inheritance, sealed methods, polymorphism. 14) Interfaces : Multiple inheritance : defining an interface, extending an interface, implementing interfaces, interfaces & inheritance, explicit interface implementation, abstract class & interfaces.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 1

15) Operator overloading : Overloadable operators, need for Operator overloading, defining Operator overloading, overloading unary operators, overloading binary Operator, overloading comparison Operators. 16) Delegates & events : Delegates , Delegate declaration, Delegate methods, Delegates instantiation, Delegates invocation, using Delegates, multicast Delegates, events. 17) Managing console I/O operations : console class, console input, console output, formatted output, numeric formatting, standard numeric format, custom numeric format. 18) Managing errors & exceptions : types of errors, exceptions, syntax of exception handling code, multiple catch statement, the exception hierarchy , general catch handler, using final statement, nested try blocks, throwing our own exceptions, checked & unchecked operators, using exceptions for debugging.

3) Introduction to C# : Evaluation of C# , characteristics of C# , applications of C# ,difference between C++ & C#, Difference between JAVA & C#.]

4) Introduction to C# environment : the .NET strategy , the origins of the .NETtechnology, the .NET framework, the common language runtime , framework base classes, user & program interfaces, Visual Studio .NET , .NET languages, benefits of the .NET approach, C# & .NET

C#1.1 IntroductionC# is a simple, modern, object-oriented, versionable, compatible, flexible, interoperable and type safe programming language originated from C and C++. It combines the prominent features of modern programming languages like C++, Java, Visual Basic, etc. It is used mainly to create .NET applications. The .NET is the most modern development platform of Microsoft that enables the development of component-based applications. The .NET platform supports more than 20 different languages and the list is growing day by day. The C# compiler is considered to be the most efficient compiler in the .NET family and a major part of the .NET base classes libraries itself are written in C#.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 2

1.2

Evolution of C#

In the past two decades C and C++ were the most powerful and widely used languages for developing commercial and business softwares. These languages were often criticized for its longer development time and hence reduced productivity. So the developer community was longing for a highly productive and powerful language for their development needs. They required an environment that supports the emerging web standards and one that provides easy integration with existing applications. To address these problems Microsoft developed a platform called .NET. The alpha version of it was released in the mid of year 2000. Also in the same year Microsoft announced their C# language as a de fact language of the .NET platform. The C# compiler is considered to be the most efficient compiler in the .NET family and a major part of the .NET base classes libraries itself are written in C#.

1.3

Characteristics of C#Simple C# was designed to be easy for the professional programmer to learn and use effectively. If you have some programming experience, you will not find C# hard to master. Also, some of the confusing concepts from C++ are either left out of C# or implemented in a clearer manner. Say for example the complex pointers in C++ are missing in C#. In C++ you have ::, . , -> operators for namespaces, member access and references respectively. But in C# a single dot ( . ) operator does all these operations.

The major characteristics of C# are:

Modern The C# is emerged as a language for writing NGWS (Next Generation Windows Services) applications. In C# memory management is automatic and is no longer a responsibility of the programmers. This automatic memory management is a responsibility of C# garbage collector. Another modern feature of C# is that it support cross language exception handling.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 3

A new data type called decimal is added in C# for monetary calculations. Another modern feature of C# is that it support a robust security model. Object-oriented C# supports major object oriented programming features such as data encapsulation, inheritance and polymorphism. It contains keywords for declaring new classes and their methods and properties and for implementing encapsulation, inheritance and polymorphism. Versionable Versioning is the process of evolving a component over time in a compatible manner. A new version of a component is source compatible with a previous version if the code that depends on the previous version can, when recompiled, work with the new version. With versioning support in place, a C# developer can guarantee that as his class library evolves, it will remain binary compatibility with existing client applications. Compatible The .NET common language specification defines a standard for interoperation between .NET languages. The C# language provides support for access to standard COM objects OLE Automation. The C# programs can natively use existing COM objects, irrespective of the language they are written in. Finally it enables you to interoperate with Cstyle APIs. Flexible In C# code can be written either in safe mode or in unsafe mode. The default for C# code is safe mode which does not support pointers. But you can declare certain classes or certain methods of classes to be unsafe which enables you to use pointers. This shows the flexibility of C# language. Interoperable C# provides support for cross language interoperability. The code produced by C# can work easily with the code produced by other ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 4

languages. This is made possible through the CLS, which defines a set of rules that every language in the .NET framework has to follow. The C# programs can natively use existing COM objects, irrespective of the language they are written in. Type safe The Common Type System provides type safety, which in turn improves code stability. It takes the following type safety measures: o You cannot use uninitialized variables. o You cannot perform unsafe casts. o It enforces overflow checking in arithmetic operations. o It does bounds checking in case of arrays. o Reference parameters that passed are type-safe

1.4

Applications of C#

The C# language can be used for a variety of applications that are supported by the .NET platform. Some of these applications include: Console application Windows applications Developing windows controls Developing ASP.NET projects Creating Web controls Providing Web services Developing .NET component library

1.5 Difference between C++ and C#Following are the differences between C# and C++.

C#

C++

1. Code can be written either in safe mode Pointers are a prominentor in unsafe mode. The default for C# feature of C++ code is safe mode which does not support pointers where as the other mode ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 5

2.

(unsafe mode) support pointers. There is no numeric equivalent for true In C++, any non-zero number and false. means true and zero means false. C++ supports it.

3. 4.

Does not support default arguments.

It detects uninitialized variables and Does not detect uninitialized generates compilation error. variables and results unpredictable results. It does not support foreach

5. 6. 7. 8.

It supports foreach loop

loop In C#, we cannot access static members In C++, we can access static via an object. The switch expression can be a string members via an object. Strings are not allowed as

switch expression. In switch case statement you cannot fall In switch case statement fall through to the next case if the case through from one case to the statement is not empty. So it requires an next case is allowed even if explicit jump statement at the end of each the case statement is not case statement. Does not support multiple inheritance empty. Very well support multiple

9. 1 0. 1 1. 1 2. 1 3. 1 4.

inheritance. Permits declaration of variable between Does not permit it goto and label. All data types in C# are inherited from Primitive data types are not object super class and therefore they are objects. objects Defining more than one variable with the Variable same in a routine is not allowed. names can be

duplicated in different code for

blocks of a routine. Special keyword override is used to No special keyword override a base class method method overriding

The types of parameters that can be In C++ value parameters and passed to a method are in, out and ref. reference parameters are

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 6

1 5.

C#

check

overflow

of

passed in a different manner. arithmetic No checked and unchecked

operations using checked and unchecked keywords available in C++. keywords.

1.61. 2. 3.

Difference between Java and C# C#C# supports struct type. C# supports indexers. C# supports static constructors

JavaJava doesnt support struct. Java doesnt support indexers. for Java doesnt supports static constructors but it provides

initialization of static variables. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

static blocks for the same. C# supports operator overloading. Java doesnt support it. C# supports delegates. Java doesnt support it. C# supports unsafe mode which supports Java doesnt support it. pointers in a program. C# uses using directive for grouping Java uses packages for the related classes together. same. C# allows variable number of parameters No equivalent keyword in to a method using params keyword. java. Arithmetic overflows can be checked No equivalent keyword in using checked statement. java. The switch expression can be an integer The switch expression can or a string. be an integer value. C# does not allow free fall_through from Java allows it. case to case. A C# interface cannot have const data A java interface can have members. const data members. Special keyword override is used to No special keyword for

override a base class method method overriding. All data types in C# are inherited from Primitive data types are not object super class and therefore they are objects. objects C# supports new modifier to hide a base Java doesnt supports new class method from a derive class method. modifier to hide a base class method from a derive class

15.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 7

method.

Questions and answersQ1) Q2) Q3) Q4) Q5) Q6) Q7) Write short notes on evolution of C# language Answer: refer section 1.2 What are the characteristics of C# language? Explain Answer: section 1.3 Explain major features of C# language Answer: section 1.3 Why C# is known as a modern language? Answer: refer section 1.3-modern Give any five applications of C# language. Answer: section 1.4 Why C# is known as a type-safe language? Answer: refer section 1.3-type-safe List some features of C++ that have been excluded in C# language. Q8) Multiple inheritance Pointers in normal mode Default arguments Global variables Macros Templates Boxing and unboxing Public properties to access instance variables. Indexers Delegates Events Automatic garbage collection Versioning Type-safety

List some features of C# that are not present in C++.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 8

Q9)

A new iteration statement called foreach to looping through the elements of an arrays or collection. Boolean data type.

State ten significant differences between C# and C++ Answer: refer section 1.6

Q10) State ten significant differences between C# and Java Answer: refer section 1.7 Q11) State some of the new features that are unique to c# language. Boxing and Unboxing. Delegate and events. Strict type-safety measures. Indexers. Versioning support.

Understanding .NET strategy2.1 The .NET StrategyIt was in July 2000, Microsoft announced their new development platform called .NET. This product was the result of their much committed research and development work for more than a decades time. The .NET platform is a framework that provides a fresh application program interface to the web services such as stock trading, banking services, insurance services etc. It also supports a number of technologies such as COM, XML, and web service protocols like SOAP, WSDL, and UDDI. It integrates presentation technologies, component technologies and data technologies on a single platform and hence enables easier development of interactive web sites. The .NET platform consist of four separate products groups: A set of languages such as VB.NET, C# and so on; a set of development tools including Visual Studio.NET; a class library for building web and windows applications; and a Common Language Runtime. A set of .NET Enterprise Servers that provides special functionality for data storage, electronic mail, e-commerce and so on. Web services.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 9

New .NET enabled non-PC devices, from cell phone to game boxes.

The Microsoft .NET solution strategy includes three key approaches as shown in the following figure.

2.2

The Origins of .NET technology 1. OLE Technology 2. COM Technology 3. .NET Technology

The three generations of component model are:

OLE Technology Microsoft developed Object Linking and Embedding technology to enable easy inter-process communications among various applications. OLE was intended primarily to embed an application within a document. Say for example; spread sheets with in word processing documents. It also enables one application to manipulate objects located in another application. COM Technology COM stands for Component Object Model. This is a technology that one uses to define components and manipulate it. In this technology a program is divided into number of independent but interoperable components each one offering a particular service. Think of COM as a shell that one wraps around components, and that define how message is passed between clients and component objects. The advantages of this technology is: It reduces the software complexity. Enables distributed development across multiple organizations and departments. It improves the software maintainability.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 10

.NET Technology The .NET technology is a very powerful and highly productive for developing windows as well as web applications. Its predecessor Microsoft COM technology provides a standard binary mechanism for inter-module communication. The unique feature of .NET is the multi-language support that it provides. Microsoft .NET provides an intermediate language called Microsoft Intermediate Language (MSIL) for cross-language integration. Compiling source program in to MSIL enforces the interoperability among various .NET languages. In addition to Intermediate Language, .NET also hosts other technologies and tools, which makes it a special environment to develop windows and web applications.

2.3

The .NET Framework

Microsoft .NET framework is the set of programming interfaces at the heart of the Microsoft .NET platform. It is in essence an environment for building, deploying, and running web services and other applications. Currently the .NET framework consist of: Common Language Runtime. A number of related class libraries, collectively known as framework class library. User and program interface (ASP.NET and Winforms).

2.4

The Common Language Runtime

The .NET Common Language Runtime is a runtime environment for programs written in C# and other .NET languages. It is responsible for loading and execution of programs, memory management, starting up and killing threads and ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 11

processes, enforcing security policy, handling exceptions, interoperability with other systems and so on. The major components of CLR are: Common Type System Common Language Specification Intermediate Language

Common Type System (CTS) The common Type System is set of storage types built in to Common Language Runtime so that a number of different programs can use them. These types are broadly classified into reference types and value types. All the languages supported by .NET platform can use these common types. So one .NET language can be called from another .NET language without any type conversion. Common Language Specification (CLS) The CLS defines a standard for interoperation between languages. The CLS is a set of rules that a language must follow to run on .NET platform. Such languages can use each others class libraries. When developers design publicly accessible APIs following the rules of CLS, those APIs can be used in any programming language supported by .NET. Microsoft Intermediate language When we compile any .NET program, it compiles source program to Microsoft Intermediate Language (MSIL) files, which the CLR then executes. The MSIL files that one .NET language produces are identical to the MSIL files that other .NET languages produce. When you execute a program MSIL file is converted to machine code by the Just In Time (JIT) compiler. The following figure shows the activities of CLR for executing a program.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 12

2.5

Managed Code

The CLR provides a runtime execution environment for .NET applications. The compilers that are compatible to the .NET platform generate code that runs under the control of the CLR. These are managed codes, because the CLR defines the rules that the codes development language must follow. The managed code generated by c# (and other compilers capable of producing managed code) is Intermediate Language (IL) code. This IL code is converted to native code by just in time compilers.

2.6

Visual Studio.NET Visual Studio.NET represents a complete development environment in the

.NET framework. This allows programmers to use languages they know and ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 13

comfortable with, to make exciting, reusable XML web services. Visual Basic, Visual C++ and C# uses the same Integrated Development Environment (IDE), which allows them to share tools and facilities in the creation of mixed language integration. 2.7 . NET Languages . NET allows cross language integration. Any language that follows common language specification can be used for .NET programming. They include: Native to .NET 2.8 C# C++ Visual Basic Jscript COBOL Eiffel Perl Python Smalltalk Mercury Scheme And many more Benefits of .NET approach It reduces the amount of code that a programmer needs to write. Microsoft .NET allows IT department to tap other vendors XML web services which reduces the internal development cost and provides better services to their customers. Interoperability with existing applications. Simple and easy to build sophisticated development tools. Integration of different languages into one platform is another benefit of .NET approach. It says be there where you are - means that use any existing language for writing .NET programs. ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 14

Third-party languages

Rich object model. Enhanced built-in functionality. Fewer bugs. The standard way of storing information is accomplished through the Common Type System (CTS). By using a common system to define ways of storing information, it is possible for different programming languages to share this information.

2.9

C# and .NET

C# is the de facto language for .NET applications. It has complete access to the rich class libraries provided by .NET SDK tools. The CLR extends a number of benefits to C# when it is implemented on the .NET platform. These include: Q1 Q2 Q3 Q4 Interoperability with other languages. Enhanced security. Versioning support. Debugging support. Automatic garbage collection. XML support for web based applications. Write short notes on the .NET strategy Answer: - Section 2.1 Write short notes on OLE and COM technology. Answer: - Refer section 2.2 OLE technology and COM technology Discuss the origin of .NET technology Answer: - Refer section 2.2. Can .NET technology support inter-module communication as COM technology does? Yes. Microsoft COM technology provides a standard binary mechanism for inter-module communication. Microsoft .NET provides an intermediate language called Microsoft Intermediate Language (MSIL) for crosslanguage integration. Compiling source program written in a language

Questions and Answers

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 15

supported by .NET platform to an Intermediate Language enforces the interoperability among various .NET languages. Q5 What does the .NET slogan be there where you are mean? One of the most important benefits of .NET approach is Integration of different languages into one platform. It says be there where you are means that use any existing language that supports Common Language Specification for writing .NET programs. This is certainty great news to the programmer community because they can use their favorite language to develop .NET applications. Q6 Q7 What is .NET framework? Answer: - Refer section 2.3. List the services provided by Common Language Runtime? Q8 Loading and execution of programs Memory management Starting up and killing threads and processes Enforcing security policy Handling exceptions Interoperability with other systems And many more

What is Common Language Runtime? The .NET Common Language Runtime is a runtime environment for .NET languages. It is responsible for loading and execution of programs, memory management, starting up and killing threads and processes, enforcing security policy, handling exceptions, interoperability with other systems and so on. The major components of CLR are: Common Type System Common Language Specification Intermediate Language Write detailed notes on the Common Language Runtime? Answer: - Refer section 2.4. What is mean by Common Language Specification?

Q9 Q10

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 16

Answer:-refer section 2.4 Topic- Common Language Specification Q11 Q12 What is the Common Type System? Answer:-refer section 2.4 Topic- Common Type System What are the tools C# provides for desktop based as well as web based applications? Q13 Q14 Windows forms Web forms Console Applications Web services

Describe the application of Visual Studio.NET Answer:-refer section 2.6. What are framework base classes? List some of the important services the Framework Base Classes can offer to the user The Framework Base Classes are those built-in classes that provide various services for application development. Following are the List of services the Framework Base Classes can offer to the user. GUI development String handling Exception handling Evaluation of mathematical functions Database management Input/Output operations File handling Networking Managing arrays, lists, maps, etc And many more

Q15 Q16

What are the benefits/advantages of .NET approach? Answer:-refer section 2.8. List the native and third part languages supported by C#. Answer:-refer section 2.7

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 17

Q17 Q18

Write short notes on Microsoft Intermediate Language or MSIL? Answer:-refer section 2.4 Microsoft Intermediate Language What is managed code? Answer:-refer section 2.5.

3.3.1

Data Type, Literals and Variables.Data Types

C# supports two general data types. They are: 1. Value Type or Simple Type 2. Reference Type A variable of value type contains a value of that type directly. Value type includes simple types, struct types and enum types. The reference types do not store the actual data they represent, but they store reference to the actual data. They include class types, interface types, delegate types, string types and array types. The value types are similar to the data types found in other programming languages like C++, Java, etc. The simple types of C# are grouped as follows: numeric type bool type char type

Numeric Data Types The Numeric types can be broadly classified in to four categories. They are: Integral Floating point Decimal

The Integral data types Integral data types store integer values. An integer number can be a signed or unsigned whole number with out a fractional part. There are nine integral types in C#. They are detailed in the following table. Integral Type Sbyte Description It can store signed 8-bit integers. Range -128 to 127

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 18

Byte Short Ushort Int Uint Long Ulong Floating-point type Floating point Type Float Double

It represents unsigned 8-bit integers. It represents signed 16-bit integers It represents unsigned 16-bit integers It represents signed 32-bit integers It represents unsigned 32-bit integers It represents signed 64-bit integers It represents unsigned 64-bit integers

0 to 255 -32768 32767 O to 65535 -2.15E+9

to

to

2.15E+9 O to 4.29E+9 -9.22E+18 to 9.22E+18 0 to 1.84E+19

Description

Range

Single-precision floating point type. It 1.5*10-45 to 3.4*1038 requires 4 bytes of memory space Double-precision floating point type. 5.0*10-324 to 1.7*10308 It requires 8 bytes of memory space

Decimal type Decimal Type Decimal Description Range

This type represents numbers used 1.0*10-28 to 7.9*1028 for financial and monetary calculations. Decimal numbers are 128 bit numbers. This data type was created for storing numbers with grater precisions. places. Operations are exact to a maximum of 28 decimal

Bool type The value of a bool type is true or false, which are C# keywords. There is no numeric equivalent for true and false. The outcome of a relational operator, such as expression2

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 36

=

=

All numeric and enumeration types define a "less than or equal to" relational operator (= expression2 The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result. The operands must be of the same type (or the right-hand operand must be implicitly convertible to the type of the left-hand operand) General Form:lhs=expression Where: lhs A storage location, property, or indexer. expression An expression.

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 37

The addition assignment operator. Assignment General Form:Lhs+=expression Where: lhs:A storage location, property, or indexer. expression:An expression. An expression using the += assignment operator, such as x += y is equivalent to x=x+y except that x is only evaluated once. Example:Int I=10; i += 5; Console.WriteLine(s); Output 15 The subtraction assignment operator. General Form:lhs-=expression; Where: lhs A storage location, property, or indexer. expression An expression. An expression using the -= assignment operator, such as x-=y is equivalent to x=x-y Example:Int I=10; i - = 5; Console.WriteLine(s); Output 5

+=

-=

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 38

The multiplication assignment operator. General Form:lhs*=expression Where: lhs A storage location, property, or indexer. expression An expression. An expression using the += assignment operator, such as x *= y is equivalent to x=x*y except that x is only evaluated once. Example:Int I=10; i *= 5; Console.WriteLine(s); Output 50 The division assignment operator. General Form:lhs/=expression; Where: lhs A storage location, property, or indexer. expression An expression. An expression using the /= assignment operator, such as x /= y is equivalent to x=x/y except that x is only evaluated once. Example:Int I=10; i /= 5; Console.WriteLine(s); Output 2

*=

/=

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 39

The modulus assignment operator. General Form:-:lhs%=expression; Where: lhs A storage location, property, or indexer. expression An expression. An expression using the %= assignment operator, such as x %= y is equivalent to x=x%y except that x is only evaluated once. Example:Int I=10; i %= 5; Console.WriteLine(s); Output 0 The conditional operator (?:) returns one of two values depending on a third value. The conditional operator is used in an expression of the following form: Conitional-expression ? expression1 : expression2 If conditional-expression is true, expression1 is evaluated and becomes the result; if conditionexpression is false, expression2 is evaluated and becomes the result. Conditional operator simplifies if condition. if(x != 0) r = Math.Sqrt(x); else r=0; The above if condition can be replaced by a conditional operator as follows: r = x != 0 ? Math.Sqrt(x) : 0; Is used for member access. It is used to create objects on the heap and invoke constructors. xyz x = new xyz();

%=

Conditional Operator

?:

. (dot) new

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 40

Special Operators

is

sizeof

The is operator is used to check whether the run-time type of an object is compatible with a given type. General Form:-: expression is type where: expression is an expression of a reference type and type is any type Example:class alpha{} class beta : alpha{} class demo { public static void Main() { alpha a=new alpha(); beta b=new beta(); System.Console.WriteLine(a is alpha); System.Console.WriteLine(b is alpha); } } Output True True The sizeof operator is used to obtain the size in bytes for a value type General Form:-: sizeof(type) Examples:sizeof(int) sizeof(float) Output:4 4

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 41

The typeof operator is used to obtain the System.Type object for a type. General Form:typeof(type) The System.Type object returned encapsulates the information associated with type. Example:class xyz{} class demo { public static void Main() { Type t=typeof(xyz); System.Console.WriteLine(t.IFullName); System.Console.WriteLine(t.IsClass); } } Output xyz True

typeof

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 42

This special operator is performs a cast operation at runtime. General Format:e as type Where e is an expression being cast to type. If the operation is successful, one can refer to the type that is returned. If the value of e is null, the result is the value null with the compile-time type T. Unlike a cast expression, the as operator never throws an exception. Example:using System.IO; using System; class alpha { public void disp() { System.Console.WriteLine("from alpha"); } } class beta : alpha {} class demo { public static void Main() { alpha a=new alpha(); beta b=new beta(); System.Console.WriteLine (b as alpha); b.disp(); } } Output From alpha

as

4.2

Type conversion

Type conversion is the process of converting data of one type to another type. The conversion of a smaller type to bigger type is called widening conversion and that of a bigger type to a smaller type is called narrowing conversion. conversions can be declared either as implicit or explicit. In C#,

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 43

Implicit Conversions The implicit conversion occurs automatically when required and is occur without any special syntax. All widening conversions are implicit conversions and are performed with out any loss of data. The following table shows the predefined implicit numeric conversions. Implicit conversions might occur in many situations, including method invoking and assignment statements. From Sbyte Byte Short Ushort Int Uint Long Char Float Ulong To short, int, long, float, double, or decimal short, ushort, int, uint, long, ulong, float, double, or decimal Int, long, float, double, or decimal Int, uint, long, ulong, float, double, or decimal long, float, double, or decimal long, ulong, float, double, or decimal float, double, or decimal ushort, int, uint, long, ulong, float, double, or decimal Double float, double, or decimal

Remember the following points regarding implicit numeric conversion: The conversions from int, uint, or long to float and from long to double may cause a loss of precision, but not a loss of magnitude. There are no implicit conversions to the char type. There are no implicit conversions between floating-point types and the decimal type. A constant expression of type int can be converted to sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant expression is within the range of the destination type.

Explicit Conversions The narrowing conversions cannot be made implicitly. If you attempt such conversions, the compiler will give an error message. An explicit conversion is needed in such situations. This can be done as follows: ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 44

destination-data-type variable-name1 = (destination-data-type) variable-name2; Example:Int x=10; byte b=(byte) x; In the above example an integer variable is explicitly converted to byte and stored in a byte location. The explicit numeric conversions are the conversions from a numeric-type to another numeric-type. From Sbyte Byte Short Ushort Int Uint Long Ulong Char Float Double The following list shows the situations where an explicit numeric conversion is needed. To byte, ushort, uint, ulong, or char. sbyte or char. sbyte, byte, ushort, uint, ulong, or char. sbyte, byte, short, or char. sbyte, byte, short, ushort, uint, ulong, or char. sbyte, byte, short, ushort, int, or char. sbyte, byte, short, ushort, int, uint, ulong, or char sbyte, byte, short, ushort, int, uint, long, or char. sbyte, byte, or short. sbyte, byte, short, ushort, int, uint, long, ulong, char, or decimal. sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or decimal. Decimal sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or double. The explicit numeric conversion may cause loss of precision or result in throwing exceptions.

Questions and AnswersQ1) Q2) Q3) Q4) Why do you need is operator? How do you use it in a program? Answer:- Refer section 4.1 sub topic is operator Why do you need as operator? How do you use it in a program? Answer:- Refer section 4.1 sub topic as operator List all special operators in C#? Explain each with its general format. Answer:- Refer section 4.1 special operators When do we use conditional operator? Explain with the help of an example Answer:- Refer section 4.1 sub topic ?: operator Q5) Describe typeof and sizeof operators

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 45

Answer:- Refer section 4.1 sub topic typeof and sizeof Q6) What is mixed mode arithmetic expression? How is it evaluated? An arithmetic expression is mixed mode if it contains operands of different type. Say for example one operand is of type real and other is integer. In an expression where one operand is of real type, then the other operand is converted to real and real arithmetic is performed. This type of conversions can occur many times in a complex mixed mode arithmetic expression. The expression 21/2.0 is a mixed mode arithmetic expression and the result 10.5. Q7) What do you mean by implicit conversion? Explain with the help of an example Answer:- Refer section 4.2 sub topic implicit conversion Q8) What do you mean by explicit conversion? Explain with the help of an example Answer:- Refer section 4.2 sub topic explicit conversion Q9) List all situations where implicit conversions occur Answer:- Refer the table in section 4.2 sub topic implicit conversion Q10) List all situations where explicit conversions occur Answer:- Refer the table in section 4.2 sub topic explicit conversion

55.1

Decision Making and BranchingDecision Making With IF Statement

The if statement selects a statement for execution based on the value of a boolean expression. The if condition is further classified into: simple if if else

The syntax for simple if is as follows: if ( boolean-expression ) statements The syntax for if else is as follows: if ( boolean-expression ) ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 46

statements else statements Examples:1) 2) if (age>=18) System.Console.WriteLine(issue a driving license); if (age>=18) { System.Console.WriteLine(issue a driving license); } else { System.Console.WriteLine(come after {0} years,(18-age)); } } In C and C++ the expression in an if condition can be integer. But in C# the expression in an if statement must result a boolean value. We cannot use integer values. So the following if condition is invalid in C#. int x=10; if(x) .. .. An if statement is executed as follows: Step1:-The boolean-expression is evaluated. Step2:-If the boolean expression yields true, control is transferred to the statement block of if part. Step3:-If the boolean expression yields false and if an else part is present, control is transferred to the statement block of else part. If the Boolean expression yields false and if an else part is not present, control is transferred to the end point of the if statement.

5.2

Nesting of IF ELSE statement

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 47

Nesting is simply the inclusion of one statement inside another. To nest an if statement, you place a second if statement within the first. You can nest within the if section or the else section. Example:int age =18; bool issued=true; if (age>=18) { if(!issued) System.Console.WriteLine("issue a driving license"); else System.Console.WriteLine("come after {0} years",(18-age)); }

5.3

The ELSE IF ladder

It is also possible to extend the if statement to handle multiple conditions using the following else-if arrangement: if (Condition1) Statement1; else if (Condition2) Statement2; else if (Condition3) Statement3; ... else StatementN; Example The following program makes use of the else-if ladder to check if the input character is lowercase, uppercase, or a number. Otherwise print The character is not alphanumeric. using System; public class Iftest ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 48

{ public static void Main() { Console.Write("Enter a character: "); char c = (char) Console.Read(); if (Char.IsUpper(c)) Console.WriteLine("The character is uppercase."); else if (Char.IsLower(c)) Console.WriteLine("The character is lowercase."); else if (Char.IsDigit(c)) Console.WriteLine("The character is a number."); else Console.WriteLine("The character is not alphanumeric."); } } Output Enter a character: A The character is uppercase.

5.4

The SWITCH statement

The switch statement is a multiple branching statement that selects one of the many alternatives. The general form of switch statement is: switch (expression ) { case value1: statements; break; case value2: statements; break; case value3: statements; ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 49

break; .. .. default: statement; break; } The expression can be any of the following types:sbyte byte short ushort int uint long ulong char string

A switch statement is executed as follows: Step1:-The switch expression is evaluated and checks whether it is a valid type. Step:- If the value specified in one of the cases is equal to the value of the switch expression, control is transferred to the statements of that case. Step3:-If none of the values specified in case labels is equal to the value of the switch expression, and if a default label is present, control is transferred to the statement list following the default statement. If none of the values specified in case labels is equal to the value of the switch expression, and if no default label is present, control is transferred to the end point of the switch statement. Example:switch (val) { case 0: System.Console.WriteLine(zero); ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 50

break; case 1: System.Console.WriteLine(one); break; default: System.Console.WriteLine(default); break; } Fall through in switch statement Unlike C and C++, execution of a switch section is not permitted to fall through to the next switch section, and the example switch (val) { case 0: System.Console.WriteLine(zero); case 1: System.Console.WriteLine(one); default: System.Console.WriteLine(default); } results in a compile-time error. When execution of a switch section is to be followed by execution of another switch section, an explicit goto case or goto default statement must be used: switch (val) { case 0: System.Console.WriteLine(zero); goto case 1; case 1: System.Console.WriteLine(one); goto default; default: ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 51

System.Console.WriteLine(default); } Multiple labels are permitted in a switch section. The example switch (i) { case 0: case 1: System.Console.WriteLine(common for 0 and 1); break; case 2: System.Console.WriteLine(two); break; default: System.Console.WriteLine(default); } is valid.

Questions and AnswersQ1) Q2) What is fallthrough in switch statement? How is it achieved in C#? Answer:- Refer section 5.4 sub topic fall through in switch statement. When will you use the conditional operator (?:) compared to if else statements? Answer:-In many occasions conditional operator?: replaces if else statement. The use of conditional operator leads concise and more efficient coding. However the readability is poor. It is not recommended when nesting of condition is required. It is always better to use if statements wherever nesting of condition is required. operator is described in section 4.1. Q3) Q4) Explain if .. else ladder with the help of a suitable example Answer:- Refer section 5.3. Explain switch statement with the help of a suitable example Answer:- Refer section 5.4. ________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 52 The conditional

________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 53

6.1

Decision Making and Looping

Loops are used to repeat an operation a number of times. The C# language supports the following types of loops. for loop while loop do while loop foreach loop

for loop________________________________________________________________ C # Notes Prepared By Prof: Agi Thomas 54

A for loop is used to repeat a specific task for a specific number of times. It is an entry-controlled loop and hence the loop condition is tested before the execution of the loop. The body of the loop will be executed only when the condition is true. The syntax for a for-loop in C# is as given below:for(initialization;condition;increment/decrement) { statements }

The execution of a for loop is as follows: Step 1) The initialization section is evaluated first. Step 2) Then the condition is tested before the execution of the loop. If it returns true value, the body of the loop is executed and if it returns false value the loop is terminated. Step 3) After executing the body of the loop, increment or decrement section is evaluated and then the control is transferred back to step 2. Example:The following code segment prints the even numbers from 2 to 100 class forloopdemo { public static void Main() { for(int i=1;i0;i--) { for(int j=1;j