Common language specification in .net pdf




















Abstraction and encapsulation are related features in object oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction. Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member.

Any public member can be accessed from outside the class. The member function Display and GetArea can also access these variables directly without using any instance of the class. The member functions Display is also declared public, so it can also be accessed fromMain using an instance of the Rectangle class, named r.

Private Access Specifier Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members.

Even an instance of a class cannot access its private members. ReadLine ; Console. The member functions AcceptDetails and Display can access these variables.

Since the member functions AcceptDetails andDisplay are declared public, they can be accessed from Main using an instance of the Rectangle class, named r. Protected Access Specifier Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. We will discuss this in more details in the inheritance chapter.

Internal Access Specifier Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.

Then what would be the default access specifier of a class member if we don't mention any? It is private. This is also used while implementing inheritance. Every C program has at least one class with a method named Main. The return type is the data type of the value the method returns.

If the method is not returning any values, then the return type is void. It cannot be same as any other identifier declared in the class. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Example Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two.

It has public access specifier, so it can be accessed from outside the class using an instance of the class. FindMax a, b ; Console. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test.

This is known as recursion. In this case, changes made to the parameter inside the function have no effect on the argument. Reference parameters This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument. Output parameters This method helps in returning more than one value.

Passing Parameters by Value This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters.

The reference parameters represent the same memory location as the actual parameters that are supplied to the method. You can declare the reference parameters using the ref keyword. Passing Parameters by Output A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function. Output parameters are similar to reference parameters, except that they transfer data out of the method rather than into it.

Output parameters are particularly useful when you need to return values from a method through the parameters without assigning an initial value to the parameter. The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable or not value type operand, where an implicit conversion is possible.

If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contigeous memory locations.

Instead of declaring individual variables, such as number0, number1, A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. The rank specifies the size of the array.

For example, double[] balance; Initializing an Array Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.

For example, for an int array all elements are initialized to 0. Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. You can also use a foreach statement to iterate through an array. The simplest form of the multidimensional array is the two-dimensional array.

Jagged arrays C supports multidimensional arrays, which are arrays of arrays. Passing arrays to You can pass to the function a pointer to an array by functions specifying the array's name without an index. Param arrays This is used for passing unknown number of parameters to a function. The Array Class Defined in System namespace, it is the base class to all arrays, and provides various properties and methods for working with arrays.

Multidimensional Arrays C allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. You can declare a 2-dimensional array of strings as: string [,] names; or, a 3-dimensional array of int variables as: int [ , , ] m; Two-Dimensional Arrays The simplest form of the multidimensional array is the 2-dimensional array. A 2- dimensional array is a list of one-dimensional arrays.

A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Initializing Two-Dimensional Arrays Multidimensional arrays may be initialized by specifying bracketed values for each row. The following array is with 3 rows and each row has 4 columns. That is, row index and column index of the array. You can verify it in the above diagram. You can declare a jagged array named scores of type int as: int [][] scores; Declaring an array, does not create the array in memory.

C param arrays or parameter arrays come into help at such times. AddElements , , , , ; Console. It is defined in the System namespace. The Array class provides various properties and methods to work with arrays. Property No. Methods of the Array Class The following table describes some of the most commonly used methods of the Array class: Sr. Methods No, 1 Clear Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.

The length is specified as a bit integer. The index is specified as a bit integer. Inherited from Object. For complete list of Array class properties and methods, please consult Microsoft documentation on C. Reverse temp ; Console. Sort list ; Console. WriteLine ; Console. However, more common practice is to use the string keyword to declare a string variable.

The string keyword is an alias for theSystem. Join " ", sarray ; Console. Methods of the String Class The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods: Sr. Methods No. However, it ignores case if the Boolean parameter is true.

The int parameter specifies the maximum number of substrings to return. WriteLine "The sequence 'test' was found. Substring 23 ; Console. It helps you to make a single variable hold related data of various data types.

The struct keyword is used for creating a structure. Structures are used to represent a record. Suppose you want to keep track of your books in a library. The struct statement defines a new data type, with more than one member for your program.

However, you cannot define a default constructor for a structure. The default constructor is automatically defined and connot be changed. Unlike classes, structs can be instantiated without using the New operator. An enumerated type is declared using the enum keyword.

C enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance. Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it.

By default, the value of the first enumeration symbol is 0. Fri; Console. This does not actually define any data, but it does define what the class name means. That is, what an object of the class consists of and what operations can be performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called members of the class.

Defining a Class A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces.

If not mentioned, then the default access specifier for a class type is internal. Default access for the members is private. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.

These variables can only be accessed using the public member functions. A constructor has exactly the same name as that of the class and it does not have any return type. Such constructors are called parameterized constructors. Destructor can be very useful for releasing memory resources before exiting the program. Destructors cannot be inherited or overloaded.

When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member. The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.

Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.

Such functions can access only static variables. The static functions exist even before the object is created. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class.

This existing class is called the base class, and the new class is referred to as the derived class. The idea of inheritance implements the IS-A relationship. Base and Derived Classes A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.

Therefore the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list. However, you can use interfaces to implement multiple inheritance. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'. Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time.

In dynamic polymorphism , it is decided at run-time. Static Polymorphism The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C provides two techniques to implement static polymorphism.

They are: 1. Function overloading 2. Operator overloading We discuss operator overloading in next chapter. Function Overloading You can have multiple definitions for the same function name in the same scope. You cannot overload function declarations that differ only by return type.

Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime. Dynamic polymorphism is implemented by abstract classes and virtual functions.

CallArea r ; c. CallArea t ; Console. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Similar to any other function, an overloaded operator has a return type and a parameter list.

It adds the attributes of two Box objects and returns the resultant Box object. WriteLine "Box1 is greater than Box2" ; else Console. WriteLine "Box1 is less than Box2" ; else Console. WriteLine "Box1 is greater or equal to Box2" ; else Console. WriteLine "Box1 is less or equal to Box2" ; else Console. WriteLine "Box1 is not less or equal to Box2" ; if Box1!

WriteLine "Box3 is equal to Box4" ; else Console. WriteLine "Box3 is not equal to Box4" ; Console. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.

Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members.

It often helps in providing a standard structure that the deriving classes would follow. Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities. Declaring Interfaces Interfaces are declared using the interface keyword. It is similar to class declaration.

Interface statements are public by default. Generic; using System. Linq; using System. The class names declared in one namespace does not conflict with the same class names declared in another. For example, we are using the System namespace in our programs. The class Console is defined there.

WriteLine "Hello there" ; We could have written the fully qualified name as: System. WriteLine "Hello there" ; You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. All preprocessor directives begin with , and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon ;.

C compiler does not have a separate preprocessor; however, the directives are processed as if there was one. In C the preprocessor directives are used to help in conditional compilation. A preprocessor directive must be the only instruction on a line. Preprocessor Directives in C The following table lists the preprocessor directives available in C : Preprocessor Description.

Directive define It defines a sequence of characters, called symbol. The define Preprocessor The define preprocessor directive creates symbolic constants. WriteLine "PI is defined" ; else Console. WriteLine "PI is not defined" ; endif Console. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the if and the next directive.

Syntax for conditional directive is: if symbol [operator symbol] Where, symbol is the name of the symbol you want to test. You can also use true and false or prepend the symbol with the negation operator. The operator symbol is the operator used for evaluating the symbol.

Conditional directives are used for compiling code for a debug build or when compiling for a specific configuration. A conditional directive beginning with a if directive must explicitly be terminated with a endif directive. Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs. Constructs for Defining Regular Expressions There are various categories of characters, operators, and constructs that lets you to define regular expressions.

Click the follwoing links to find these constructs. By "m", "n" in default, the match is case- "moon" sensitive. Wildcard: Matches any single a. WriteL ine "? The dog ran. The sun is out. Zero-width negative? Matches the previous element zero "rai? Matches the previous element zero "rai?? Matches the? The following table lists the alternation constructs: Alternation Description Pattern Matches construct Matches any one th e is at "the", "this" element separated by in "this is the the vertical bar day.

Matches yes if? Expression is interpreted as a zero- width assertion. Miscellaneous Constructs The following table lists various miscellaneous constructs: Construct Definition Example? Act" ? Matches words at the first closing parenthesis. The comment? The Regex Class The Regex class is used for representing a regular expression. It has the following commonly used methods: Sr. For the complete list of methods and properties, please read the Microsoft documentation on C.

Example 1 The following example matches words that start with 'S': using System; using System. Replace input, replacement ; Console. A C exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C exception handling is built upon four keywords: try, catch, finally, and throw. It is followed by one or more catch blocks. The catch keyword indicates the catching of an exception. For example, if you open a file, it must be closed whether an exception is raised or not.

This is done using a throw keyword. Syntax Assuming a block raises an exception, a method catches an exception using a combination of the try and catch keywords. Exception Classes in C C exceptions are represented by classes. The exception classes in C are mainly directly or indirectly derived from the System. Exception class. Some of the exception classes derived from the System. Exception class are the System. ApplicationException and System.

SystemException classes. The System. ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class. SystemException class is the base class for all predefined system exception. The following table provides some of the predefined exception classes derived from the Sytem. IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range. ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type.

NullReferenceException Handles errors generated from deferencing a null object. DivideByZeroException Handles errors generated from dividing a dividend with zero. InvalidCastException Handles errors generated during typecasting. OutOfMemoryException Handles errors generated from insufficient free memory. StackOverflowException Handles errors generated from stack overflow.

Handling Exceptions C provides a structured solution to the exception handling in the form of try and catch blocks.

Using these blocks the core program statements are separated from the error-handling statements. These error handling blocks are implemented using the try, catch, and finally keywords. DivideByZeroException: Attempted to divide by zero. User-defined exception classes are derived from the ApplicationException class. When a file is opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing through the communication path.

There are two main streams: the input stream and the output stream. The input stream is used for reading data from file read operation and the output stream is used for writing into the file write operation. IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc.

The following table shows some commonly used non-abstract classes in the System. BinaryWriter Writes primitive data in binary format. BufferedStream A temporary storage for a stream of bytes. Directory Helps in manipulating a directory structure.

DirectoryInfo Used for performing operations on directories. DriveInfo Provides information for the drives. File Helps in manipulating files. FileInfo Used for performing operations on files. FileStream Used to read from and write to any location in a file. Path Performs operations on path information. StreamReader Used for reading characters from a byte stream. StreamWriter Is used for writing characters to a stream.

StringReader Is used for reading from a string buffer. StringWriter Is used for writing into a string buffer. IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an existing file. Open, FileAccess.

Read, FileShare. OpenOrCreate, FileAccess. Write F. Close ; Console. However, to utilize the immense powers of C System. IO classes, you need to know the commonly used properties and methods of these classes. Topic and Description Reading from and Writing into Text files It involves reading from and writing into text files. Privacy policy. NET provides a run-time environment, called the common language runtime, that runs the code and provides services that make the development process easier.

Compilers and tools expose the common language runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code. Managed code benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.

Compilers and tools are able to produce output that the common language runtime can consume because the type system, the format of metadata, and the run-time environment the virtual execution system are all defined by a public standard, the ECMA Common Language Infrastructure specification.

To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in your code. Metadata is stored with the code; every loadable common language runtime portable executable PE file contains metadata. The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set run-time context boundaries.

The runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. Objects whose lifetimes are managed in this way are called managed data. Garbage collection eliminates memory leaks as well as some other common programming errors. If your code is managed, you can use managed data, unmanaged data, or both managed and unmanaged data in your. NET application. Because language compilers supply their own types, such as primitive types, you might not always know or need to know whether your data is being managed.

The common language runtime makes it easy to design components and applications whose objects interact across languages. Objects written in different languages can communicate with each other, and their behaviors can be tightly integrated. For example, you can define a class and then use a different language to derive a class from your original class or call a method on the original class. You can also pass an instance of a class to a method of a class written in a different language.

Here, in this project we want to use the C class library project, so first add a reference to the CsharpClassLibrary project. Then create a class with the name TestClass and copy-paste the following code in it. Now, when you try to build the VB Class Library project, you will get the below error. This is because VB is not case sensitive and it found two methods with the same name.

That means we are violating the Common Language Specifications in the C code. Now, let us change the second method name to Calculate2 as shown below. With the above changes in place, now, build the VB class library project and the build should succeed as expected. Now, you may have one question, how to check whether the code is CLSCompliant or not. Once you open the AssemblyInfo. Step1: Import the System namespace as using System;. With the above changes in place in the AssemblyInfo.

Now, when you build the C Class Library Project you will get the following warning. In the next article, I am going to discuss the Managed and Unmanaged Code in.



0コメント

  • 1000 / 1000