Anda di halaman 1dari 9

C# Notes

What is C#? C# pronounced as C Sharp) is a new computer-programming language developed by Microsoft Corporation, USA. C# is a fully object-oriented programming language like java and is the first Compenentoriented language. It has been designed to support the key feature of .Net Framework. It is a simple, efficient productive and type-safe language derived from the popular C and C++ language. Why C#? C and C++ have been the two most popular and most widely used languages in the software industry for the past two decades. They provide programmers with a tremendous amount of power and control developing scientific, commercial and business applications. However, these languages suffer from a number of shortcomings in meeting the merging World Wide Web requirements and standards. Of concern are the following: The high complexity of the language. Their long cycle-time They are not truly object-oriented They are not suitable for working with new web technologies. They have poor type-safety They are prone to costly programming errors They do not support versioning They are prone to memory leakages Their low productivity Their poor interoperability with the existing systems. They are weak in consistency Their poor support for component programming.

Visual Basic (VB), a language promoted by Microsoft for overcoming these problems, also could not meet some of the requirements of the www. Java, a language derived from C/C++ family, however, is truly object-oriented and has been widely used for web applications for the past five years. Unfortunately, Java has not retained some powerful C++ features such as operator overloading. It also lacks inter-operability with code developed in other languages. Although Microsoft attempted to transform Java and make it a language of choice for their proposed new generation .NET platform. Microsoft wanted an environment that is completely in tune with current and emerging Web-programming practices and one that easily integrates with existing systems. Microsoft therefore decided to design a new language starting with a clean slate. The result is C#, a simple and modern language that directly addresses the needs of component-based software development. Characteristics of C# As pointed out earlier, the main design goal of C# was simplicity rather than pure power. C# fulfills the need for a language that is easy to write, read and maintain and also provides the power and flexibility of C++. The language that is designed for both computing and communications is characterized by several key features.

Jav a

C+ + C#

V B

Its is Simple C# simplifies C++ by eliminating irksome operators such as ->,:: and pointers. C# treats integer and Boolean data types as two entirely different types. This means that the use of = in place of ==in If statement will be caught by the compiler. Consistent C# supports a unified type system which eliminates the problem of varying ranges of integer types. All types are treated as objects and developers can extend the type system simply and easily. Modern C# is called a modern language due to a number of features it supports. It supports Automatic garbage collection Rich intrinsic model for error handling Decimal data type for financial applications. Modern approach to debugging and Robust security model Simple Consistent Modern Object-oriented Type-safe Versionable Compatible Interoperable and Flexible

Object-Oriented C# is truly object-oriented. It supports all the three tenets of object-oriented systems, namely. Encapsulation Inheritance and Polymorphism The entire C# class model is built on top of the Virtual Object System (VOS) of the .NET framework In C#, everything is an object. There are no more global functions, variables and constants. Type-safe Type-safety promotes robust programs. C# incorporates a number of type-safe measures. All Dynamically allocated objects and arrays are initialized to Zero. Use of any uninitialized variables produces an error message by the compiler. Access to arrays are range-checked and warned if it goes out-of-bounds C# does not permit unsafe casts C# enforces overflow checking in arithmetic operations. Reference parameters that are passed are type-safe. C# supports automatic garbage collection.

Versionable Making new versions of software modules work with the existing applications is known are versioning. C# provides support for versioning with the help of new and override keywords. With this support, a programmer can guarantee that his new class library will maintain binary compatibility with the existing client applications. Compatible C# enforces the .NET common language specifications and therefore allows inter-operation with other .NET languages. C# provides support for transparent access to standard COM and OLE Automation. C# also permits interoperation with C-Style APIs.

Flexible Although C# does not support pointers, we may declare certain classes and methods as unsafe and then use pointers to manipulate them. However, these codes will not be type-safe. Inter-operability C# provides the support the using COM objects, no matter what language was used to another them. C# also supports a special feature that enables a program to call out any native API. Applications of C# As pointed out earlier, C# is a new language developed exclusively to suit the features of .NET platform. It can be used for a variety of applications that are supported by the .NET platform. Console applications Windows applications Developing windows controls Developing ASP.NET projects Creating Web Controls Providing Web Services Developing .NET component library

They also added a number of additional features to make C# a type-safe and web-enabled language. The Origins of .NET Technology Before going into the details of .NET features further, we shall see how the concept of .NET was evolved over the past ten years. The current technology of .NET has gone through three significant phases of development:

OLE technology COM technology .NET technology

These developments that took place during the 1990s are illustrated. OLE Technology OLE (Object Linking and Embedding) technology was developed by Microsoft in the early 1990s to enable easy interprocess communications. OLE provided support to achieve the following: To embed documents from one application into another application To enable one application to manipulate objects located in another application.

This enabled users to develop applications which required inter-operability between various products such as MS Word and MS Excel. COM Technology Till the advent of COM technology, the monolithic approach had been used for developing software. But when programs become too large and complex, the monolithic approach leads to a number of problems in terms of maintainability and testing of software. To overcome these problems, Microsoft introduced the componentbased model for developing software programs. In the component-based approach, a program is broken into a number of independent components where each one offers a particular service. Each component can be developed and tested independently and then integrated it into the main system. This technology is known as the Component Object Model (COM) and the software built using COM is referred to as componentware. COM technology offers a number of benefits to developers and users. It Reduces the overall complexity of software Enables distributed development across multiple organizations or departments and Enhance software maintainability.

.NET Technology .NET technology is third-generation component model. This provides a new level of inter-operability compared to COM technology. COM provides a standard binary mechanism for inter-model communication. This mechanism is replaced by an intermediate language called Microsoft Intermediate Language (MSIL) or simply IL in the .NET Technology. Various .NET-language compilers enforce inter-operability by compiling code into IL, which is automatically compatible with other IL modules. An inherent characteristic of IL code is metadata. Metadata is data about data and describes its characteristics, including data types and locations. IL allows for true crosslanguage integration. In addition to IL, .NET includes a host of other technologies and tools that will enable us develop and implement Web-based applications easily. Common Language Runtime The Common Language Runtime, popularly known as CLR is the heart and soul of the .NET Framework. It also supports cross-language interoperability. The CLR provides a number of services that include. Loading and execution of programs Memory isolation for applications Verification of type safety Compilation of IL into native executable code Providing metadata Memory management (automatic garbage collection) Enforcement of security Interoperability with other systems Managing exceptions and errors Support for tasks such as debugging and profiling

Common Type System (CTS) The .NET framework provides multiple language support using the feature known as Common Type System that is built into the CLR. The CTS supports a variety of types and operations found in most programming languages and therefore calling one language from another does not require type conversions. Although C# is specially designed for the .NET Platform, we can build .NET programs in a number of other languages including C+ + and Visual Basic. Common Language Specification (CLS) The Common Language Specification defines a set of rules that enables interoperability on the .NET platform. These rules serve as a guide to third-party compiler designers and library builders. Application Programming Interfaces (APIs) that are designed following the rules of CLS can easily be used by all the .NET Languages. Microsoft Intermediate Language (MSIL) MSIL, or simply IL, is an instruction set into which all the .NET programs are compiled. It is akin to assembly language and contains instructions for loading, storing, initializing and calling methods. When we compile a C# program or any program written in a CLS-compliant language, the source code is compiled into MSIL. Managed Code As we know, the CLR is responsible for managing the execution of code compiled for the .NET platform. The code that satisfies the CLR at runtime in order to execute is referred to as managed code. Compilers that are compatible to the .NET platform generate managed code. For example, the C# compiler generates managed code. The managed code generated by C# (and other compilers capable of generating managed code) is IL code. The IL code is then converted to native machine code by the JIT compilers. .NET Languages The .NET framework is language neutral. Currently, we can use a number of languages for developing .NET applications. They include: Native to .NET C# (Specially created for .NET) C++ Visual Basic Jscript

Third-party languages COBOL Eiffel Perl Python Small Talk Mercury Scheme

C# and the .NET C# is a new programming language introduced with .NET. It is a concise, elegant .NET language. The CLR extends a number of benefits to C# when it is implemented on the .NET platform. These include: Interoperability with other languages Enhanced security Versioning support Debugging support Automatic garbage collection XML support for web-based applications.

C# can be used to develop two categories of programs, namely, Executable application programs and Component libraries

Compile Time Errors No matter how thoroughly the design is carried out, and no matter how much care is taken in coding, we can never say that a program is totally error-free. A program may contain two types of errors: Syntax Errors Logic Errors

While syntax error will be caught by the compiler, logic errors should be eliminated by testing the program logic carefully. When the compiler cannot interpret what we are attempting to convey through our code the result is syntax error. C# program is a collection of tokens, comments and white spaces. C# includes the following five types of Keywords Identifiers Literals Operators Punctuators

tokens.

Keywords:

Abstract, as, base, bool and etc., Punctuators:

Parentheses( ) Braces { } Brackets [ ] Semicolon; Colon: Comma, Period.

Literals: Numeric literals Boolean literals Character Literals

Numeric Literals Integer literals There are two types of integers, namely, decimal integers and hexadecimal integers. Decimal integers consist of a set of digits, 0 through 9 and embedded spaces, commas and non-digit characters are not permitted between digits. Hexadecimal integer it may also include alphabets A through F or a through f. 0x2 0x9f Real literals A whole number, a decimal point, a fractional part, an exponent Boolean Literals There are two Boolean literal values: True, False

Character Literals


Data Types Value Types

Single Character literals 5, x String literals Hello C#, 2001

Value Types Pointers Reference Types

Predefined Type Integers, Real Numbers, Booleans, Characters

User-defined Types Enumerations, Structures

Reference Types Predefined types Objects, Strings User-defined Types Classes, Arrays, Delegates, Interfaces Boxing and Unboxing In object-oriented programming, methods are invoked using object. Since value types such as int and long are not objects, we cannot use them to call methods. Boxing means the conversion of a value type on the stack to a object type on the heap. Object type back to a value type is known as unboxing. Boxing Value or reference can be assigned to an object without an explicit conversion. Int m=10; Object om=m; M=20; Console.Writeline (m); //m=20 Console.Writeline (Om); //Om=10 Unboxing Process of converting the object type back to the value type. In contrast to boxing, unboxing is an explicit operation using C-style casting. Int m=10; Object om=m; //box m Int n=(int)om; // unbox om back to an int

C# supports a rich set of operators. C# operators can be classified into a number of related categories as below: Arithmetic Operators Relational Operators Logical Operators Assignment Operators Increment and decrement Operators Conditional Operators Bitwise Operators Special Operators Arithmetic Operators Integer Arithmetic Real Arithmetic Mixed-mode Arithmetic +,-,*,/,% Relation Operators : <, <=,>,>=, ==, ! = Logical Operators: &&, ||, !, &,|, ^ Assignment Operators Increment and Decrement Operators : ++ and Conditional Operator: ?:

Type Conversions Implicit Conversions Explicit Conversions Methods in C# In object-oriented programming, objects are used as building blocks in developing a program. The code designed to work on the data is known as methods in C#. C# is a pure object-oriented language and therefore, every method must be contained with a class remember, in other language like VB,C and C++, we can define global functions that are not associated with a particular class. Declaring Methods Methods declaration has five parts: Name of the method (methodname) Type of value the method return(type) List of parameters (formal-parameter-list) Body of the method Method modifiers (modifier) Method modifiers New: Public: Protected: Internal: Private: Static: Virtual: Abstract: Override: Sealed: Extern: The method hides an inherited method with the same signature. The method can be accessed from anywhere, including outside the class. The method can be accessed from within the class to which it belongs, or a type derived from that class. The method can be accessed from within the same program. The method can only be accessed from inside the class to which it belongs The method does not operate on a specific instance of the class. The method can be overridden by a derived class. A virtual method which defines the signature of the method, but doesnt provide an implementation. The method overrides an inherited virtual or abstract method The method overrides an inherited virtual method, but cannot be overridden by any classes which inherit from this class. Must be used in conjunction with override The method is implemented externally, in a different language.

The Main Method As mentioned earlier, C# programs start execution at a method named Main(). This method must be the static method of a class and must have either int or void as return type Public static int Main() or Public static void Main()

Invoking Method Once methods have been defined, they must be activated for operations. The process of activating method is known as invoking or calling. Here, object name is the name of the object on which we are calling the method method name. the actualparameter-list is a comma separated list of Actual values (or expressions) that must match in type, order and number with the formal parameter list of the methodname declared in the class. Note that the invoking statement is an executable one and therefore must end with a semicolon. The values of the actual parameters are assigned to the formal parameters at the time of invocation. Nesting of methods The class Nesting defines two method namely Largest() and Max(). The Method Largest() calls the method Max() to determine the largest of the two numbers and then displays the result. Method parameters Value Parameters Reference Parameters Output Parameters Parameter arrays

Methods Overloading C# allows us to create more than one method with the same name, but with the different parameter line and different definitions. This is called method overloading. Method overloading is used when methods are required to perform similar task but using different input parameters. Overloaded methods must differ in number and/or type of parameters they take. This enables the compiler to decide which one of the definitions to execute depending on the type and number of arguments in the method call. Note that the methods return type does not play any role in the overload resolution. Using the concept of method overloading, we an design a family of methods with one name but different arguments lists. For example, an overloaded add() method handles different types of data as shown below. Basic Principles of OOP All object-Oriented languages employ three core principles, namely, Encapsulation Encapsulation provides the ability to hide the internal details of an object from its users. The outside user may not be able to change the state of an object directly. However, the state of an object maybe altered indirectly using what are known accessor and mutator methods. In C#, encapsulation is implemented using the access modifier keywords public, private, and protected. The concept of encapsulation is also know as data hiding or information hiding. When done properly, we can create software black boxes that can be independently tested and used. Inheritance Inheritance is the concept we use to built new classes using the existing class definitions. Through inheritance we can modify a class the way we want to create new objects. The original class is known as base or parent class and the modified one is known as derived class or subclass or child class. The concept of inheritance facilitates the reusability of existing code and thus improves the integrity of programs and productivity of programmers. Polymorphism Polymorphism is the third concept of OOP. It is the ability to take more than one form. For example, an operation may exhibit different behavior in different situations. The behavior depends upon the types of data used in the operation. For example, an addition operation involving two numeric values will produce a sum and the same addition operation will produce a string if the operands are string value instead of numbers. Similarly, a method when called with one set of parameters may draw a circle but when called with another set of parameters may draw a triangle. Polymorphism is extensively used while implementing inheritance. Encapsulation Inheritance and Polymorphism

Constructors We know that all objects that are created must be given initial values. We have done this earlier using two approaches. The first approach uses the dot operator to access to instance variables and then assigns values to them individually. It can be a tedious approach to initialize all the variables of all the objects. The second approach takes the help of a function like GetData to initialize each object individually using statement like. Inheritance and Polymorphism It is always nice if we could reuse something that already exists rather than creating the same over again. C#, being a pure object-oriented language, supports this feature. In fact, the ability to create new classes from the existing classes is the major motivation and power behind using OOP languages. C# classes can be reused in several ways. Reusability is achieved by designing new classes, reusing all or some of the properties of existing ones. The mechanism of designing or constructing one class from another is called inheritance. This may be achieved in two different forms. Classical form Containment form Inheritance Types Single Inheritance(only one base class) Multiple Inheritance (several base classes) Hierarchical Inheritance (one base class, many subclasses) Multilevel Inheritance Derived from a derived class)

Class members Visibility Programs Counting with if Statement Using system; Class IfTest { Public static void main() { Int I, count, count1, count2; Float [] weight= {45.0F, 55.0F, 47.0F} Float [] height= {176.5F, 174.2F, 168.0F} Public Protected Private Internal Protected internal

Anda mungkin juga menyukai