Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1. What is .NET? It is a platform neutral framework. It is a layer between the operating system and the programming language. It supports many programming languages, including VB.NET, C# etc. .NET provides a common set of class libraries, which can be accessed from any .NET based programming language. There will not be separate set of classes and libraries for each language. If you know any one .NET language, you can write code in any .NET language!! In future versions of Windows, .NET will be freely distributed as part of operating system and users will never have to install .NET separately.
2. What is Not? .NET is not an operating system. .NET is not a programming language.
3. ".NET is a framework" Confused with this definition? We cannot define .NET as a 'single thing'. It is a new, easy, and extensive programming platform. It is not a programming language, but it supports several programming languages. By default .NET comes with few programming languages including C# (C Sharp), VB.NET, J# and managed C++. .NET is a common platform for all the supported languages. It gives a common class library, which can be called from any of the supported languages. So, developers need not learn many libraries when they switch to a different language. Only the syntax is different for each language. When you write code in any language and compile, it will be converted to an 'Intermediate Language' (Microsoft Intermediate Language - MSIL). So, your compiled executable contains the IL and not really executable machine language. When the .NET application runs, the .NET framework in the target computer take care of the execution. (To run a .NET application, the target computer should have .NET framework installed.) The .NET framework converts the calls to .NET class libraries to the corresponding APIs of the Operating system.
3.1 Is it platform independent? Many people ask this question "Java is platform independent, what about .NET?. The answer is "Yes" and "No! The code you write is platform independent, because whatever you write is getting compiled into MSIL. There is no native code, which depends on your operating system or CPU. But when you execute the MSIL, the .NET framework in the target system will convert the MSIL into native platform code. So, if you run your .NET exe in a Windows machine, the .NET framework for Windows will convert it into Windows native code and execute. If you run your .NET application in Unix or Linux, the .NET framework for Unix/Linux will convert your code into Unix/Linux native code and execute. So, your code is purely platform independent and runs anywhere! But wait, we said it wrong... there is no .NET framework for UNIX or Linux available now. Microsoft has written the .NET framework only for Windows. If you or some one else write a .NET framework for other platforms in future, your code will run there too. So, let us wait until someone write .NET framework for Linux before you run your .NET code in Linux.
3.2 Major Issues before .NET Registration of COM components. Unloading COM components Versioning Problem (DLL Hell)
The .NET Platform The .Net platform is a set of technologies. Microsoft .NET platform simplify software development (Windows or WEB) by building applications of XML Web services. The .NET platform consists of the following core technologies which are refer as components of .NET: The .NET Framework The .NET Enterprise Servers Building block services Visual Studio .NET
Application
The .NET Platform Architecture 3.3 Components of .NET Framework The .Net Framework consists of: Common Language Runtime Class Libraries Support for Multiple Programming Language
.NET Compliant Languages (VC++, VB.NET, ASP.NET, C# and other third party languages)
.NET Framework Base Class Library (ADO.NET, XML, Threading, Diagnostics, IO, Security, etc.) Common Language Runtime (Memory Management, Common Type System, Garbage Collector) Components of .NET Framework
4. Application Development and Execution .NET is a multilingual platform then any .NET based language can be chosen to develop applications. 4.1 Choosing a Compiler According to the language we can choose its run time aware compiler for .NET platform. Because it is a multilingual execution environment, the runtime supports a wide variety of data types and language features. 4.2 Compiling to MSIL
Source Code
Compiler
Class loader
JIT Compiler
Trusted preJIT code only Managed Native Code Call to an uncompiled method
Execution
Security checks
Runtime Engine
Source code to native code and code execution When compiling source code, the compiler translates it into an intermediate code represented in MSIL. Before code can be run, MSIL code must be converted to CPU-specific code, usually by a
The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and Common object file format (COFF) used historically for executable content. The file format, which accommodates MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images. 4.3 Compiling MSIL to Native Code Before you can run Microsoft intermediate language (MSIL), it must be compiled against the common language runtime to native code for the target machine architecture. The .NET Framework provides two ways to perform this conversion: A .NET Framework just-in-time (JIT) compiler. The .NET Framework Ngen.exe (Native Image Generator). 4.4 Compilation by the JIT Compiler JIT compilation converts MSIL to native code on demand at application run time, when the contents of an assembly are loaded and executed. Because the common language runtime supplies a JIT compiler for each supported CPU architecture, developers can build a set of MSIL assemblies that can be JIT-compiled and run on different computers with different machine architectures. However, if your managed code calls platform-specific native APIs or a platformspecific class library, it will run only on that operating system. JIT compilation takes into account the possibility that some code might never be called during execution. Instead of using time and memory to convert all the MSIL in a PE file to native code, it converts the MSIL as needed during execution and stores the resulting native code in memory so that it is accessible for subsequent calls in the context of that process. The loader creates and attaches a stub to each method in a type when the type is loaded and initialized. When a method is called for the first time, the stub passes control to the JIT compiler, which converts the MSIL for that method into native code and modifies the stub to point directly to the generated native code. Therefore, subsequent calls to the JIT-compiled method go directly to the native code. Install-Time Code Generation Using NGen.exe Because the JIT compiler converts an assembly's MSIL to native code when individual methods defined in that assembly are called, it affects performance adversely at run time. In most cases, that diminished performance is acceptable. More importantly, the code generated by the JIT compiler is bound to the process that triggered the compilation. It cannot be shared across multiple processes. To allow the generated code to be shared across multiple invocations of an application or across multiple processes that share a set of assemblies, the common language runtime supports an ahead-of-time compilation mode. This ahead-of-time compilation mode uses the Ngen.exe (Native Image Generator) to convert MSIL assemblies to native code much like the JIT compiler does. However, the operation of Ngen.exe differs from that of the JIT compiler in three ways: It performs the conversion from MSIL to native code before running the application instead of while the application is running.
It compiles an entire assembly at a time, instead of one method at a time. It persists the generated code in the Native Image Cache as a file on disk. 4.5 Summary of Managed Code Execution Process The process of compiling and executing managed code is given below: -
1. When you compile a program developed in a language that targets the CLR, instead of
compiling the source code into machine-level code, the compiler translates it into Microsoft Intermediate Language (MSIL) or Intermediate language (IL). This ensures language interoperability. In addition to translating the code into IL, the compiler also produces metadata about the program during the process of compilation. Metadata contains the description of the program, such as classes and interfaces, the dependencies and the versions of the components used in the program. The IL and the metadata are linked in assembly. The compiler creates the .EXE or .DLL file. When you execute the .EXE or .DLL file, the code (converted to IL) and all the other relevant information from the base class library is sent to the class loader. The class loader loads the code in the memory. Before the code can be executed, the .NET framework needs to convert the IL into native or CPU-specific code. The Just-in-time (JIT) compiler translates the code from IL to managed native code. The CLR supplies a JIT compiler for each supported CPU architecture. During the process of compilation, the JIT compiler compiles only the code that is required during execution instead of compiling the complete IL code. When an uncompiled method is invoked during execution, the JIT compiler converts the IL for that method into native code. This process saves the time and memory required to convert the complete IL into native code. During JIT compilation, the code is also checked for type safety. Type safety ensures that objects are always accessed in a compatible way. Therefore, if you try to pass an 8-byte value to a method that accepts a 4-byte value as a parameter, the CLR will detect and trap such an attempt. Type safety also ensures that objects are safely isolated from each other and are therefore safe from any malicious corruption. After translating the IL into native code, the converted code is sent to the .NET runtime manager. The .NET runtime manager executes the code. While executing the code, a security check is performed to ensure that the code has the appropriate permissions for accessing the available resources.
2.
3. 4. 5.
6.
7.
8. 9.
Common Language Infrastructure (CLI) The Common Language Infrastructure (CLI) is an open specification developed by Microsoft that describes the executable code and runtime environment that allows multiple high-level languages to be used on different computer platforms without being rewritten for specific architectures. The common language Infrastructure (CLI) is a theoretical model of a development platform that provides a device and language independent way to express data and behavior of applications. The CLI specification describes the following four aspects: The Common Type System (CTS)
The CTS supports two general categories of types: 1. Value Types Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in, user-defined or enumerations types. 2. Reference Types Reference types store a reference to the values memory address, and are allocated on the heap. Reference types can be self-describing types, pointers type or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types are user-defined classes, boxed value types, and delegates. A set of data types and operations that are shared by all CTS-compliant programming languages. Metadata
Information about program structure is language-agnostic, so that it can be referenced between languages and tools, making it easy to work with code written in a language you are not using. Common Language Specification (CLS)
A set of base rules to which any language targeting the CLI should conform in order to interoperate with other CLS-compliant languages. The CLS rules define a subset of the Common Type System. Virtual Execution System (VES)
The VES loads and executes CLI-compatible programs, using the metadata to combine separately generated pieces of code at runtime. The Common Language Runtime The CLR is one of the most essential components of the .NET framework. The CLR or the runtime provides functionality such as exception handling, security, debugging, and versioning support to any language that targets it. The CLR can execute programs written any language. You can use the compilers to write the code that runs in the managed execution environment provided by the CLR. The code that is developed with a language compiler that targets the CLR is managed code. On the other hand, the code that is developed without considering the conventions and requirements of the common language run time is called unmanaged code.
Automatic Memory Management: The CLR provides the garbage collection feature for managing the lifetime of an object. This process relieves a programmer of the task of manual memory management by deallocating the blocks of memory associated with objects that are no longer being used. The objects whose lifetime is managed by the garbage collection process are called managed data. Standard Type System: The CLR implements a formal specification called Common Type System (CTS). The CTS is an important part of the support provided by the CLR for cross-language integration because it provides a type system that is common across all programming languages. It also defines the rules that ensure that objects written in different languages can interact with each other. Language Interoperability: Language interoperability is the ability of an application to interact with another application written in a different programming language. Language interoperability helps maximize code reuse. For example, you can write a class in Visual Basic and inherit it in a code written in Visual C++. Platform Independence: When you compile a program developed in language that targets the CLR, the compiler translates the code into an intermediate language. This language is CPU-independent. This means that the code can be executed from any platform that supports the .NET CLR. Security Management The traditional operating system security model provides permissions to access resources, such as memory and data, based on user accounts. In .NET platform security is achieved through the Code Access Security (CAS) model. The CAS model specifies what the code can access instead of specifying who can access resources. Type Safety: This feature ensures that objects are always accessed in compatible ways. Therefore the CLR will prohibit a code from assigning a 10-byte value to an object that occupies 8 bytes.
Advantages of the .NET Framework Consistent programming model Multi-platform applications Multi-Language integration Automatic Resource Management Ease of deployment
OOPS & C# The skeleton of object - oriented programming is of course the concepts of class. The C# on OOPS explains classes and their importance in implementation of object oriented principles. Any language can be called object oriented if it has data and method that use data encapsulated in items named objects. An object oriented programming method has many advantages; some of them are flexibility and code reusability. Key Concepts of Object Orientation Abstraction Encapsulation Inheritance Polymorphism
Abstraction is the ability to generalize an object as a data type that has a specific set of
characteristics and is able to perform a set of actions. Object-oriented languages provide abstraction via classes. Classes define the properties and methods of an object type. Examples: You can create an abstraction of a dog with characteristics, such as color, height, and weight, and actions such as run and bite. The characteristics are called properties, and the actions are called methods. A Recordset object is an abstract representation of a set of data. Classes are blueprints for Object. Objects are instance of classes.
Object References
When we work with an object we are using a reference to that object. On the other hand, when we are working with simple data types such as Integer, we are working with the actual value rather than a reference. When we create a new object using the New keyword, we store a reference to that object in a variable. For instance: Draw MyDraw = new Draw; This code creates a new instance of Draw. We gain access to this new object via the MyDraw variable. This variable holds a reference to the object. Now we have a second variable, which also has a reference to that same object. We can use either variable interchangeably, since they both reference the exact same object. The thing we need to remember is that the variable we have is not the object itself but, rather, is just a reference or pointer to the object itself.
Early binding means that our code directly interacts with the object, by directly calling its methods. Since the compiler knows the object's data type ahead of time, it can directly compile code to invoke the methods on the object. Early binding also allows the IDE to use IntelliSense to aid our development efforts; it allows the compiler to ensure that we are referencing methods that do exist and that we are providing the proper parameter values. Late binding means that our code interacts with an object dynamically at run-time. This provides a great deal of flexibility since our code literally doesn't care what type of object it is interacting with as long as the object supports the methods we want to call. Because the type of the object isn't known by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is possible but we get unprecedented flexibility in exchange. If we enable strict type checking by using Option Strict On at the top of our code modules, then the IDE and compiler will enforce early binding behavior. By default, Option Strict is turned off and so we have easy access to the use of late binding within our code.
Access Modifiers
Access Modifiers are keywords used to specify the declared accessibility of a member of a type.
Public is visible to everyone. A public member can be accessed using an instance of a class, by
a class's internal code, and by any descendants of a class.
Private is hidden and usable only by the class itself. No code using a class instance can access
a private member directly and neither can a descendant class.
10
Protected members are similar to private ones in that they are accessible only by the containing
class. However, protected members also may be used by a descendant class. So members that are likely to be needed by a descendant class should be marked protected.
Internal/Friend is public to the entire application but private to any outside applications. Internal
is useful when you want to allow a class to be used by other applications but reserve special functionality for the application that contains the class. Internal is used by C# and Friend by VB .NET.
11
Protected Internal may be accessed only by a descendant class that's contained in the same
application as its base class. You use protected internal in situations where you want to deny access to parts of a class functionality to any descendant classes found in other applications.
s Composition of an OBJECT
We use an interface to get access to an object's data and behavior. The object's data and behaviors are contained within the object, so a client application can treat the object like a black box accessible only through its interface. This is a key object-oriented concept called Encapsulation. The idea is that any programs that make use of this object won't have direct access to the behaviors or data-but rather those programs must make use of our object's interface.
12
There are three main parts of Object: 1. Interface 2. Implementation or Behavior 3. Member or Instance variables
Interface
The interface is defined as a set of methods (Sub and Function routines), properties (Property routines), events, and fields (variables or attributes) that are declared Public in scope.
Implementation or Behavior
The code inside of a method is called the implementation. Sometimes it is also called behavior since it is this code that actually makes the object do useful work. Client applications can use our object even if we change the implementation-as long as we don't change the interface. As long as our method name and its parameter list and return data type remain unchanged, we can change the implementation all we want. So Method Signature depends on: Method name Data types of parameters Either Parameter is passed ByVal or ByRef. Return type of method
It is important to keep in mind that encapsulation is a syntactic tool-it allows our code to continue to run without change. However, it is not semantic-meaning that, just because our code continues to run, doesn't mean it continues to do what we actually wanted it to do.
13
}
Above listing shows defines an interface named IMyInterface. All the methods of Interface are public by default and no access modifiers (like private, public) are allowed with any method of Interface. Using an Interface: InterfaceImplementer.cs class InterfaceImplementer : IMyInterface { public void MethodToImplement() { Console.WriteLine("MethodToImplement() called."); } } The InterfaceImplementer class in above listing implements the IMyInterface interface. Indicating that a class inherits an interface is the same as inheriting a class. In this case, the following syntax is used: class InterfaceImplementer : IMyInterface Note that this class inherits the IMyInterface interface; it must implement its all members. While implementing interface methods all those needs to be declared public only. It does this by implementing the MethodToImplement() method. Notice that this method implementation has the exact same signature, parameters and method name, as defined in the IMyInterface interface. Any difference will cause a compiler error.
Inheritance is the idea that one class, called a subclass, can be based on another class, called
a base class. Inheritance provides a mechanism for creating hierarchies of objects. Inheritance is an important object-oriented concept. It allows you to build a hierarchy of related classes, and to reuse functionality defined in existing classes. Inheritance is the ability to apply another class's interface and code to your own class. Normal base classes may be instantiated themselves, or inherited. Derived classes can inherit base class members marked with protected or greater access. The derived class is specialized to provide more functionality, in addition to what its base class provides. Inheriting base class members in derived class is not mandatory. C# supports two types of Inheritance mechanisms: 1) Implementation Inheritance 2) Interface Inheritance What is Implementation Inheritance? - When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance What is Interface Inheritance?
14
Types of Inheritance
1. Single Inheritance 2. Multilevel Inheritance 3. Multiple Inheritance (Implementation is possible through Interface) 4. Hierarchical Inheritance
Class A
Class A
Class B
Single Inheritance
Class B
Class C
Hierarchical Inheritance
Class D
Class A Class B
Class A
Class B
Example: Single Inheritance: public class A { } Multilevel Inheritance: public class A { } Hierarchical Inheritance: public class A { }
15
{ }
public class C : A, B
{ }
Polymorphism
Polymorphism is the ability to define a method or property in a set of derived classes with matching method signatures but provide different implementations and then distinguish the objects' matching interface from one another at runtime when you call the method on the base class. It is a feature to use one name in many forms. It can be achieved in following ways: Method Overloading Method Overriding Method Hiding
Method overriding and hiding makes use of the following three method keywords 1. new 2. virtual 3. override
1. When a derived class inherits from a base class, it gains all the methods, fields, properties and
events of the base class. To change the data and behavior of a base class, you have two choices: you can replace the base member with a new derived member, or you can override a virtual base member. Replacing a member of a base class with a new derived member requires the new keyword. If a base class defines a method, field, or property, the new keyword is used to create a new definition of that method, field, or property on a derived class. The new keyword is placed before the return type of a class member that is being replaced. For example: public class BaseClass { public void DoWork() { } public int WorkField; public int WorkProperty { get { return 0; } } } public class DerivedClass : BaseClass { public new void DoWork() { } public new int WorkField; public new int WorkProperty
16
2,3. In order for an instance of a derived class to completely take over a class member from a
base class, the base class has to declare that member as virtual. This is accomplished by adding the virtual keyword before the return type of the member. A derived class then has the option of using the override keyword, instead of new, to replace the base class implementation with its own. For example: public class BaseClass { public virtual void DoWork() { } public virtual int WorkProperty { get { return 0; } } } public class DerivedClass : BaseClass { public override void DoWork() { } public override int WorkProperty { get { return 0; } } } DerivedClass B = new DerivedClass(); B.DoWork(); // Calls the new method. BaseClass A = (BaseClass)B; A.DoWork(); // Also calls the new method.
17
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override. An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier. You cannot use the modifiers new, static, virtual, or abstract to modify an override method. An overriding property declaration must specify the exact same access modifier, type, and name as the inherited property, and the overridden property must be virtual, abstract, or override.
18
The new modifier is permitted on nested classes. The new modifier can be used to modify a nested type if the nested type is hiding another type. The public, protected, internal, and private modifiers control the accessibility of the class. Depending on the context in which the class declaration occurs, some of these modifiers may not be permitted The abstract modifier is used to indicate that a class is incomplete and that it is intended to be used only as a base class. An abstract class differs from a non-abstract class in the following ways: An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class. While it is possible to have variables and values whose compile-time types are abstract, such variables and values will necessarily either be null or contain references to instances of non-abstract classes derived from the abstract types. An abstract class is permitted (but not required) to contain abstract methods and members. An abstract class cannot be sealed.
Features of Abstract Methods: An abstract method is implicitly a virtual method. Abstract method declarations are only permitted in abstract classes. Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:
19
Copypublic abstract void MyMethod(); The implementation is provided by an overriding method, which is a member of a nonabstract class. It is an error to use the static or virtual modifiers in an abstract method declaration.
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax. It is an error to use the abstract modifier on a static property. An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier. An abstract class must provide implementation for all interface members. Example: // abstract_keyword.cs // Abstract Classes using System; abstract class MyBaseC // Abstract class { protected int x = 100; protected int y = 150; public abstract void MyMethod(); // Abstract method public abstract int GetX // Abstract property { get; } public abstract int GetY // Abstract property { get; } } class MyDerivedC: MyBaseC { public override void MyMethod() { x++; y++; } public override int GetX // overriding property { get { return x+10; } } public override int GetY // overriding property { get
20
21
Constructors generally following types: Default Constructor Parameterized constructor Private Constructor Static Constructor Copy Constructor
Default Constructor A constructor that takes no parameters is called a default constructor. When a class is initiated default constructor is called which provides default values to different data members of the class. You need not to define default constructor it is implicitly defined.
Example: -
class Program { class C1 { int a, b; public C1() { this.a = 10; this.b = 20; } public void display() { Console.WriteLine("Value of a: {0}", a); Console.WriteLine("Value of b: {0}", b); } } static void Main(string[] args) { C1 ob1 = new C1(); ob1.display(); Console.ReadLine(); }
Output: - Value of a: 10
22
Parameterized constructor Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.
class Program { class C1 { int a, b; public C1(int x, int y) { this.a = x; this.b = y; } public void display() { Console.WriteLine("Value of a: {0}", a); Console.WriteLine("Value of b: {0}", b); } } static void Main(string[] args) { // Here when you create instance of the class // parameterized constructor will be called C1 ob1 = new C1(10,20); ob1.display(); Console.ReadLine();
} }
Output: - Value of a: 10 Value of b: 20 Private Constructor Private constructors are used to restrict the instantiation of object using 'new' operator. A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If you don't want the class to be inherited we declare its constructor private. We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private. We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.
23
Static Constructors C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor). Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster. Static constructors are used to initializing class static data members. Point to be remembered while creating static constructor: 1. There can be only one static constructor in the class. 2. The static constructor should be without parameters. 3. It can only access the static members of the class. 4. There should be no access modifier in static constructor definition. Static members are preloaded in the memory. While instance members are post loaded into memory. Static methods can only use static data members.
24
class Program { class c1 { int a, b; public c1(int x, int y) { this.a = x; this.b = y; } // Copy construtor public c1(c1 a) {
25
Remember that a destructor can't have any modifiers like private, public etc. If we declare a destructor with a modifier, the compiler will show an error. Also destructor will come in only one form, without any arguments. There is no parameterized destructor in C#.
Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible for garbage collection, when it is no longer used by the active part of the program. Execution of destructor may occur at any time after the instance or object becomes eligible for destruction.
26
Operator Overloading Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type. In another way, Operator overloading is a concept in which operator can define to work with the user defined data types such as structs and classes in the same way as the pre-defined data types. There are many operators which can not be overloaded, which are listed below: Conditional Operator &&, || Compound Assignment +=, -=, *=, /=, %= Other Operators [], ( ), =, ?:, ->, new, sizeof, typesof.
public class Item { public int i; public Item(int j) { i = j; } public static Item operator +(Item x, Item y) { Console.WriteLine("OPerator +" + x.i + "" + y.i); Item z = new Item(x.i + y.i); return z; } } class Program { static void Main(string[] args) { Item a = new Item(10); Item b = new Item(5); Item c; c = a + b; Console.WriteLine(c.i); Console.Read(); } }
Output: Operator + 10 5
27
class Complex { private int x; private int y; public Complex() {} public Complex(int i, int j) { x = i; y = j; } public void ShowXY() { Console.WriteLine("{0}\t{1}",x,y); } public static Complex operator -(Complex c) //PASSING OBJECT { Complex temp = new Complex(); temp.x = -c.x; temp.y = -c.y; return temp; } } class Program { static void Main(string[] args) { Complex c1 = new Complex(10, 20); c1.ShowXY(); // displays 10 & 20 Complex c2 = new Complex(); c2.ShowXY(); // displays 0 & 0
28
} }
Output: 10 20 0 0 -10 -20
Namespace:
Namespaces are C# program elements designed to help you organize your programs. They also provide assistance in avoiding name clashes between two sets of code. In Microsoft .Net, Namespace is like containers of objects. They may contain unions, classes, structures, interfaces, enumerators and delegates. Main goal of using namespace in .Net is for creating a hierarchical organization of program. In this case, you need not to worry about the naming conflicts of classes, functions, variables etc., inside a project. In Microsoft .Net, every program is created with a default namespace. This default namespace is called as global namespace. But the program itself can declare any number of namespaces, each of them with a unique name. The advantage is that every namespace can contain any number of classes, functions, variables and also namespaces etc., whose names are unique only inside the namespace. The members with the same name can be created in some other namespace without any compiler complaints from Microsoft .Net. To declare namespace C# .Net has a reserved keyword namespace. If a new project is created in Visual Studio .NET it automatically adds some global namespaces. These namespaces can be different in different projects. But each of them should be placed under the base namespace System. The names space must be added and used through the using operator, if used in a different project. A namespace has the following properties:
They organize large code projects. They are delimited with the . operator. The using directive means you do not need to specify the name of the namespace for every class. The global namespace is the "root" namespace: global::system will always refer to the .NET Framework namespace System.
Now have a look at the example of declaring some namespace: namespace SampleNamespace { class SampleClass{} interface SampleInterface{} struct SampleStruct{} enum SampleEnum{a,b} delegate void SampleDelegate(int i);
29
Namespaces implicitly have public access and this is not modifiable. It is possible to define a namespace in two or more declarations. For example, the following example defines two classes as part of the MyCompany namespace: namespace MyCompany.Proj1 { class MyClass { } } namespace MyCompany.Proj1 { class MyClass1 { } }
Example: The following example shows how to call a static method in a nested namespace:
using System; namespace SomeNameSpace { public class MyClass { static void Main() { Nested.NestedNameSpaceClass.SayHello(); } } // a nested namespace namespace Nested { public class NestedNameSpaceClass { public static void SayHello()
30
31
Interface An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can not contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public and they cannot include any access modifiers. An interface has the following properties: An interface is like an abstract base class: any non-abstract type that implements the interface must implement all its members. An interface cannot be instantiated directly. Interfaces can contain events, indexers, methods, and properties. Interfaces contain no implementation of methods. Classes and structs can implement more than one interface. An interface itself can inherit from multiple interfaces.
interface IPoint { int x { get; set; } int y { get; set; } } namespace Ex_Interface { class MyPoint:IPoint { private int myX; private int myY; public MyPoint(int x, int y) { myX= x; myY=y; } public int x { get { return myX; } set { myX=value; } }
32
33
Delegates In .NET, you use delegates to call event procedure. Delegates are objects that you use to call the methods of other objects. Delegates are said to be object-oriented function pointers since they allow a function to be invoked indirectly by using a reference to the function. However, unlike function pointers, the delegates in .NET are reference types, based on the class System.Delegate. In addition, delegates in .NET can reference both shared and instance methods.
In another way, a delegate can be defined as a type safe function pointer. You use delegates
to call the methods of other objects. They are object-oriented function pointers since they allow a function to be invoked indirectly by using a reference to the function. Where are Delegates used? The most common example of using delegates is in events. You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place. This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate. Starting Threads/Parallel Processing:
34
You defined several methods and you wish to execute them simultaneously and in parallel to whatever else the application is doing. This can be achieved by starting new threads. To start a new thread for your method you pass your method details to a delegate. Generic Classes: Delegates are also used for generic class libraries which have generic functionality defined. However the generic class may need to call certain functions defined by the end user implementing the generic class. This can be done by passing the user defined functions to delegates. Creating and Using Delegates: Using delegates is a two step process..........1) Define the delegate to be used ..........2) Create one or more instances of the delegate Syntax for defining a delegate: delegate string reviewStatusofARegion(); to define a delegate we use a key word delegate followed by the method signature the delegate represents. In the above example string reviewStatusofARegion(); represents any method that returns a string and takes no parameters. Syntax for creating an instance of the delegate: reviewStatusofARegion = new reviewStatusofARegion(myClass.getEurope); private string getEurope() { return Doing Great in Europe; } To create an instance of the delegate you call its constructor. The delegate constructor takes one parameter which is the method name. The method signature should exactly match the original definition of the delegate. If it does not match the compiler would raise an Error. C# provides support for Delegates through the class called Delegate in the System namespace. Delegates are of two types. Single-cast delegates Multi-cast delegates
A Single-cast delegate is one that can refer to a single method whereas a Multi-cast delegate can refer to and eventually fire off multiple methods that have the same signature. The signature of a delegate type comprises are the following.
35
A delegate is either public or internal if no specifier is included in its signature. Further, you should instantiate a delegate prior to using the same. The following is an example of how a delegate is declared. Listing 1: Declaring a delegate public delegate void TestDelegate(string message); The return type of the delegate shown in the above example is "void" and it accepts a string argument. Note that the keyword "delegate" identifies the above declaration as a delegate to a method. This delegate can refer to and eventually invoke a method that can accept a string argument and has a return type of void, i.e., it does not return any value. Listing 2: Instantiating a delegate TestDelegate t = new TestDelegate(Display);
Implementing Delegates in C#
This section illustrates how we can implement and use delegates in C#.This section illustrate how we can implement and use delegates in C#.
Example 1: Single Cast Delegate namespace Ex_Delegate { delegate int Operation(int x, int y); //declaration class Metaphor { public static int Add(int a, int b) { return a + b; } public static int Sub(int a, int b) { return a - b; } public static int Mul(int a, int b) { return a * b; } } class Program { static void Main(string[] args) { // Delegate instances Operation opr1 = new Operation(Metaphor.Add); Operation opr2 = new Operation(Metaphor.Sub); Operation opr3 = new Operation(Metaphor.Mul); //invoking of delegates int ans1 = opr1(200, 100); int ans2 = opr2(200, 100); int ans3 = opr3(20, 10); Console.WriteLine("\n Addition:" + ans1);
36
namespace Ex_MulticastDelegate { public delegate void TestDelegate(); class Program { public static void Display1() { Console.WriteLine("This is first method"); } public static void Display2() { Console.WriteLine("This is second method"); } static void Main(string[] args) { TestDelegate t1 = new TestDelegate(Display1); TestDelegate t2 = new TestDelegate(Display2); t1 = t1 + t2; // Make t1 a multi-cast delegate t1(); //Invoke delegate Console.Read(); }}}
37
It is also possible to create new ones by extending the System.Attribute class. For example: using System; [CLSCompliant(true)] Public class myClass { // class code } Web services also make use of attributes. The attribute [WebMethod] is used to specify that a particular method is to be exposed as a web service. Why Attributes ? The reason attributes are necessary is because many of the services they provide would be very difficult to accomplish with normal code. You see, attributes add what is called metadata to your programs. When your C# program is compiled, it creates a file called an assembly, which is normally an executable or DLL library. Assemblies are self-describing because they have metadata written to them when they are compiled. Via a process known as reflection, a program's attributes can be retrieved from its assembly metadata. Attributes are classes that can be written in C# and used to decorate your code with declarative information. This is a very powerful concept because it means that you can extend your language by creating customized declarative syntax with attributes. How it is used in C#? Attributes are elements that allow you to add declarative information to your programs. This declarative information is used for various purposes during runtime and can be used at design time by application development tools. For example, there are attributes such as DllImportAttribute that allow a program to communicate with the Win32 libraries. Another attribute, ObsoleteAttribute, causes a compile-time warning to appear, letting the developer know that a method should no longer be used. When building Windows forms applications, there are several attributes that allow visual components to be drag-n-dropped onto a visual form builder and have their information appear in the properties grid. Attributes are also used extensively in securing .NET assemblies, forcing calling code to be evaluated against pre-defined security constraints. These are just a few descriptions of how attributes are used in C# programs.
38
Predefined attributes
Example: Pre-defined attributes are used to store external information into metadata. For example, consider the following piece of code:
public class testAttribute { [DllImport("sampleDLL.dll")] public static extern sampleFunction(int sampleNo, string sampleString ); public static void Main( ) { string strVar; sampleFunction(10, Test Attribute); } }
Using the example code above, you can import a method called sampleFunction from sampleDLL.dll and use it in your program as if its your own method. This is achieved using the pre-defined attribute DllImport.
39
40
41
The first step is to create an object of this class. Since there is only one constructor we have no choice but to use it.
Here is how to create the socket: m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP); AddressFamily is an enum defined in Sockets namespace.
Next we need to specify socket type: and we would use reliable two way connectionbased sockets (stream) instead of un-reliable Connectionless sockets ( datagrams) . So we obviously specify stream as the socket type and finally we are using TCP/IP so we would specify protocol type as TCP. Once we have created a Socket we need to make a connection to the server since we are using connection-based communication. To connect to the remote computer we need to know the IP Address and port at which to connect. In .NET there is a class under System.Net namespace called IPEndPoint which represents a network computer as an IP address and a port number.
42
Here is the code: System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("10.10.101.200"); System.Net.IPEndPoint remoteEP = new IPEndPoint (ipAdd,8221); m_socClient.Connect (remoteEP); Description These three lines of code will make a connection to the remote host running on computer with IP 10.10.101.200 and listening at port 8221. If the Server is running and started ( listening ), the connection will succeed. If however the server is not running an exception called SocketException will be thrown. If you catch the exception and check the Message property of the exception in this case you see following text: "No connection could be made because the target machine actively refused it." Similarly if you already have made a connection and the server somehow dies, you will get following exception if you try to send data. "An existing connection was forcibly closed by the remote host" Assuming that the connection is made, you can send data to other side using the Send method of the Socket class. Send method has several overloads. All of them take a byte array. For example if you want to send "Hello There" to host you can use following call: try { String szData = "Hello There"; byte[] byData = System.Text.Encoding.ASCII.GetBytes(szData); m_socClient.Send(byData); } catch (SocketException se) { MessageBox.Show ( se.Message ); } Note that the Send method is blocking. What it means the call will block till the data has been sent or an exception has been thrown. There is a non-blocking version of the send which we will discuss in the next part of this article.
43
44
Error Handling
Overview of Exception Handling Exceptions are error conditions that arise when the normal flow of a code path-that is, a series of method calls on the call stack-is impractical. Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements
45
46
47
48
The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications. System.OutOfMemoryException System.NullReferenceException Syste.InvalidCastException Syste.ArrayTypeMismatchException System.IndexOutOfRangeException System.ArithmeticException System.DevideByZeroException System.OverFlowException
User-Defined Exceptions In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes. //C#: Exception Handling: User defined exceptions using System; class MyException : Exception { public MyException(string str) { Console.WriteLine("User defined exception");} } class MyClient { public static void Main() { try { throw new MyException("RAJESH"); } catch(Exception e) {Console.WriteLine("Exception caught here" + e.ToString()); } Console.WriteLine("LAST STATEMENT"); } } ------------------x-------------------------x------------------------------x-------------------------x-----------------------
49
File Handling in C# File handling is an unmanaged resource in your application system. It is outside your application domain (unmanaged resource). It is not managed by CLR. Data is stored in two ways, persistent and non-persistent manner. When you open a file for reading or writing, it becomes stream.
Stream: Stream is a sequence of bytes traveling from a source to a destination over a communication path. The two basic streams are input and output streams. Input stream is used to read and output stream is used to write. The System.IO namespace includes various classes for file handling. The parent class of file processing is stream. Stream is an abstract class, which is used as the parent of the classes that actually implement the necessary operations. The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.
Object
System.IO System
MarshalByref Object
System.IO
FileSystemInfo
System.IO
FileInfo
Directoryinfo
File
Path
Directory
DriveInfo
50
The following table describes some commonly used classes in the System.IO namespace: Class Name FileStream BinaryReader BinaryWriter StreamReader StreamWriter StringReader StringWriter DirectoryInfo FileInfo Description It is used to read from and write to any location within a file It is used to read primitive data types from a binary stream It is used to write primitive data types in binary format It is used to read characters from a byte Stream It is used to write characters to a stream It is used to read from a string buffer It is used to write into a string buffer It is used to perform operations on directories It is used to perform operations on files
Reading and Writing in the text file StreamWriter Class The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a writer, which can write a series of characters. The following table describes some of the methods used by StreamWriter class: Methods Close Flush Write WriteLine Description Close the current StreamWriter object and underlying stream Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream. Writes to the Stream Writes data specified by the overloaded parameters, followed by end of line.
Program to write user input to a file using StreamWriter Class using System; using System.Text; using System.IO; namespace FileWriting_SW { class Program {
51
class FileWrite { public void WriteData() { FileStream fs = new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); Console.WriteLine("Enter the text which you want to write to the file"); string str = Console.ReadLine(); sw.WriteLine(str); sw.Flush(); sw.Close(); fs.Close(); } } static void Main(string[] args) { FileWrite wr = new FileWrite(); wr.WriteData(); } } } StreamReader Class The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader, which can read series of characters. The following table describes some methods of the StreamReader class: Methods Close Peek Read ReadLine Seek Description Closes the object of StreamReader class and the underlying stream, and release any system resources associated with the reader Returns the next available character but doesn't consume it Reads the next character or the next set of characters from the stream Reads a line of characters from the current stream and returns data as a string Allows the read/write position to be moved to any position with the file
52
Program to read from a file using StreamReader Class using System; using System.IO; namespace FileReading_SR { class Program { class FileRead { public void ReadData() { FileStream fs = new FileStream ("c:\\test.txt", FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader (fs); Console.WriteLine("Program to show content of test file"); sr.BaseStream.Seek(0, SeekOrigin.Begin); string str = sr.ReadLine(); while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); } Console.ReadLine(); sr.Close(); fs.Close(); } } static void Main(string[] args) { FileRead wr = new FileRead(); wr.ReadData(); } } }
53
Introduction to Web Services A Web service exposes a number of methods that provide functionality that can be one or more application, regardless of the programming languages, operating systems, and hardware platforms used to develop them. The methods that provide such functionality are called Web Methods. The functionality exposed by a Web service can be accessed by applications by using Internet Standards, such as Simple Object Access Protocol (SOAP). SOAP is a protocol that uses extensible Markup Language (XML) to describe data and HyperText Transfer Protocol (HTTP) to transmit application data. An application that uses a Web service is called a Web Service Client. A Web service is similar to a component that provides a specific functionality. However, components uses object model-specific protocols, such as Internet Inter-ORB Protocol (IIOP) and Remote Method Invocation (RMI), for communicating with client applications. This communication approach requires a similar infrastructure at both client and the server sides. This approach is acceptable when the use of components is confined to controlled environments. Web services use Internet Standards, such as HTTP and XML, to communicate with client applications. This communication approach makes Web services independent of any language or platform. Any computer that has access to the Internet can easily access a Web service. Depending on the requirements of a business, different types of Web services can be created and used in an application. Enabling Technologies used in Web Services A web service can be created using any programming language in the .NET suite. There are certain requirements need to be fulfilled to enable applications to access the functionality provided by Web services. The requirements are: A common data representation format in order to ensure the interoperability of the data exchanged by the client application and the Web service. A standard method for sending messages from the client application to the Web service and vice versa. A standard format for describing the web service. A mechanism to allow client applications to discover the Web services and their locations.
To cater these requirements, various standards such as XML, SOAP and Web Services Description Language (WSDL) are used. XML A client passes arguments to a method exposed by a Web service. The method performs some action on the arguments and returns the results to the client application. The data returned by the Web service can be used by the client application, regardless of the hardware and software platform used to develop the application. To enable this kind of data interchange, you require a standard data representation format that can be understood by any platform. Since XML is a plain-text format that can be understood by any kind of device. SOAP To be able to communicate with each other, a Web service and a client application must agree upon a common protocol. SOAP is a standard communication protocol for interchanging information in a structured format in a distributed environment. The information exchanged
54
UDDI (Universal Description Discovery and Integration) UDDI provides a standard mechanism to register and discover a Web Service. When a Web service provider wants to make a Web service available to client applications, the provider describes the web service by using a WSDL document. Then, the provider registers the Web service in the UDDI Directory. The UDDI directory contains pointers to the Web service and the WSDL document for the Web service. Client applications can then discover the Web service by using the UDDI Directory. WSDL Document
UDDI Registry
55
XML (eXtensible Markup Language) XML is a text based markup language that enables you to store data in a structured format by using meaningful tags. The term eXtensible implies that you can extend your ability to describe a document by defining meaningful tags for your application. XML is a cross-platform, hardware and software independent markup language. XML allows computers to store data in a format that can be interpreted by any other computer system and therefore. XML can be used to transfer structured data between heterogeneous systems. XML is used as a common data interchange format in a number of applications. Advantages of XML Some of the advantages offered by XML are as follows: It provides a way of creating domain-specific vocabulary. It allows data interchange between different computer systems. It enables smart searches. It provides user-selected view of data. It allows granular updates.
Structure of XML document Before storing data in XML document, It need to organize. An XML document is composed of a number of components that can be used for representing information in a hierarchical order. These components are: Processing Instruction
An XML document usually begins with the XML declaration statement also called the Processing Instruction (PI). The PI provides information regarding the way in which the XML file should be processed. The PI statement can be written as: <? Xml version=1.0 encoding UTF-8?> The PI is optional. The PI uses the encoding property to specify the information about the encoding scheme that is used to create the XML file. The encoding scheme is the standard character set for a language. UTF-8 is the standard character set that is used to create pages written in English. This character set uses eight bits of information to represent each character. Therefore, UTF-8 stands for an 8-bit character set. Tag
Tags are used to specify a name for a given piece of information. It is a means of identifying data. Data is marked-up using tags. A tag consists of an opening and a closing angular bracket (<>). These brackets enclose the name of the tag. Tags usually occur in pairs. <P> Nick Peter </P> In this example, <p> is a predefined HTML tag or mark-up. As XML allows you to create your own tags, the same information can be stored in the following way:
56
Elements are the basic units that are used to identify and describe data in XML. They are the building blocks of an XML document. Elements are represented using tags. XML allows you to provide meaningful names to elements, which helps improve the readability of the code. For example: <Authorname> Vivek </Authorname> In the example, the Authorname element is used to store the names of authors. In this case, the element name provides a description of the content within the tags. An XML document must always have a root element. A root element contains all other elements in the document. Content
The information that is represented by the elements of an XML document is referred to as the content of that element. For example, <BOOKNAME> the painted Hose</BOOKNAME> The name of the book The Painted House is the content of the BOOKNAME element. XML enables to declare and use elements that can contain different kinds of information. An element can contain any of the following types of content: Character or data content Element content Combination or mixed content
Examples Character content <BOOKNAME> the painted Hose</BOOKNAME> Element content <Author> <Fname> John </Fname> <Lname> Smith </Lname> </Author> Mixed Content <PRODUCTDESCRIPTION> The product is available inn four colors. <COLOR> RED </COLOR> <COLOR> BLUE </COLOR> <COLOR> GREEN </COLOR> <COLOR> YELLOW </COLOR>
57
Attributes
Attributes provide additional information about the elements for which they are declared. An attribute consists of a name-value pair. Consider the following example: <PRODUCTNAME PROID=P001> DOLL</PRODUCTNAME> In this example, the element PRODUCTNAME has an attribute called PROID. The value of this attribute is set to 001. Elements can have one or more attributes. Attributes or attribute values can be either mandatory or optional. In general, an element is used to represent a definable unit. An attribute is used to represent data that further qualifies the element. For example, an element called font could have an attribute called color that is used to specify the color of the font. Entity
An entity can be described as a shortcut to a set of information. It is name that is associated with a block of data. This data can be a chunk of text or a reference to an external file that contains textual or binary information. <DISPLAY> The price of the this toy is < 20 <DISPLAY> In the example, < internal entity is used to display a less than (<) symbol. Comment
Comments are statements that are used to explain the code. They are also used to provide documentation information about an XML file or even the application to which the file belongs. When the code is executed, comment entries are ignored by the parser. Comments are created using an opening angular bracket followed by an exclamation mark and two hyphens (<!--). This is followed by the text that comprises the comments. The comment entry can be closed using two hyphens followed by a closing angular bracket (-->). Example: <! -- Productdata is the root element -->
Rules for Creating Well-formed XML document Every start tag must have an end tag. Empty tags must be closed using a forward slash (/). All attribute values must be given in double quotation marks. Tags must nest correctly. XML tags are case-sensitive. They must match each other in every implementation.
58
Rule for Naming Elements and Attribute in XML A name consists of at least one letter: a to z, or A to Z. An element name may start with an underscore (_). One or more letters, digits, hyphens, underscores or full stops can follow the initial letter. Spaces and tabs are not allowed in element names, and the only punctuation signs allowed.
An element can be empty, unrestricted, or a container element. The following table describes each type of element:
Element Type
Empty Unrestricted Container
Description
Empty elements have no content and are marked up as <emptyelement/> The opposite of an empty element is an unrestricted element, which can contain any element declared elsewhere in the DTD. Elements can contain character data and other elements
59
Description Used to represent plain text values Used to assign a unique value to each element in the document. The ID must begin with an alphabetic character. Used to assign a specific range of values. These values are specified within parenthesis
In addition to specifying the value type of an attribute, you also need to specify whether the attribute is optional or mandatory. Look at the following table for attribute types: Attribute Type REQUIRED FIXED IMPLIED Description If the attributes of an element is specified as #REQUIRED, then the value for that attribute must be specified each time the element is used in the XML document. If the attribute of an element is specified as #FIXED, then the value of the attribute can not be changed in XML document. If the attribute of an element is specified as #IMPLIED, then the attribute is optional. An IMPLIED attribute can take text strings as their values.
Method to validate the structure of data To validate the structure of data stored in an XML document against the DTD, you need to use parsers. Parsers are software programs that check the syntax used in an XML file. There are two types of parsers. They are: -
60
Non-validating parsers A non-validating parser checks if a document follows the XML syntax rules. It builds a tree structure from the tags used in an XML document and returns an error only when there is a problem with the syntax of the document. Non-validating parsers process a document faster because they do not have to check every element against a DTD. The Expat parser is an example of a non-validating parser. Validating parsers A validating parser checks the syntax, builds the tree structure, and compares the structure of the XML document with the structure specified in the DTD associated with the document. Microsoft MSXML parser is an example of a validating parser. XML Tags Examples para The para tag works like <br> or <p> in html to structure the text into paragraphs. It can be used to break a line of continuous text, or to wrap a segment of text into a paragraph. <para/> or <para>...</para> /// The <c>para</c> tag works like <![CDATA[<br> or <p>]]> in html to /// structure the text into paragraphs.<para/>It can be used to break a line /// of continuous text, <para>or to wrap a segment of text into a paragraph.</para> param The param tag is used to describe the parameters of the method. Parameter tags are automatically inserted into the header template if parameters are in the syntax. The name of the parameter is automatically inserted into the parameter tag. The parameter description should be brief. <param name="...">...</param> /// <param name="_value"> /// Used to demonstrate the usage of <c>param</c> /// </param> see Assigns a hyperlink to the specified text. <see href|cref|langword="..."/> or <see href="...">...</see> /// See <see cref="T:System.Enum">enumeration</see> /// See <see cref="M:TutorialXmlDocumentationTags.code">code</see> /// See <see href="http://www.microsoft.com">Microsoft</see> ///<see langword="null"/> seealso Adds a link to the "See Also" section.
61
Managed pointers: These pointers can point to data contained in the object heap managed by the garbage collector. These pointers are not used explicitly by the C# code. They are thus used implicitly by the C# compiler when it compiles methods with out and ref arguments. Unmanaged function pointers: The pointers are conceptually close to the notion of delegate. Unmanaged pointers: These pointers can point to any data contained in the user addressing space of the process. The C# language allows to use this type of pointers in zones of code considered unsafe.
Compilation options to allow unsafe code Unsafe code must be used on purpose and you must also provide the /unsafe option to the csc.exe compiler to tell it that you are aware that the code you wish to compile contains zones which will be seen as unverifiable by the JIT compiler. Visual Studio offers the Build Allow unsafe code project property to indicate that you wish to use this compiler option. Declaring unsafe code in C# In C#, the unsafe keyword lets the compiler know when you will use unsafe code. It can be used in three situations:
62
2.
63
64