O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

CSharp Presentation

Próximos SlideShares
Introduction to c#
Introduction to c#
Carregando em…3

Confira estes a seguir

1 de 113 Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)


Semelhante a CSharp Presentation (20)


Mais recentes (20)

CSharp Presentation

  1. 1. Microsoft Visual C#<br />Ch. Vishwa Mohan<br />Freelance Software Consultant &<br />Corporate Trainer<br />
  2. 2. Table of Contents<br />Introduction<br />Lesson 01: Getting Started <br />Lesson 02: Operators, Types, and Variables<br />Lesson 03: Control Statements <br />Lesson 04: Namespaces<br />Lesson 05: Objects and Types<br />Lesson 06: Methods <br />Lesson 07: Introduction to Classes<br />Lesson 08: Structs<br />Lesson 09: Class Inheritance<br />Lesson 10: Interfaces<br />Lesson 11: Polymorphism<br />Lesson 12: Arrays & Indexers<br />Lesson 13: Operators & Casts <br />Lesson 14: Overloading Operators <br />Lesson 15: Delegates and Events<br />Lesson 16: Generics <br />Lesson 17: Collections <br />Lesson 18: Memory Management <br />Lesson 19: Attributes & Type class. <br />Lesson 20: Exceptions <br />
  3. 3. C# Basics<br />
  4. 4. C# Basics<br />The C# compiler specially targets .NET. Which means that all code written in C# will always runs within the .NET Framework. Consequently,<br /><ul><li>The architecture and methodologies of C# reflects the underlying methodologies of .NET.
  5. 5. In many cases, language features of C# actually depends upon the features of .NET or .NET base classes. </li></ul>C# is a language is based upon the modern object oriented design methodology. It is designed to generates the code that targets .NET environment. But it is not itself part of .NET. <br />C# syntax is very much similar to C++ or Java. <br />Like C, C++, C# is case sensitive and highly type safe language.<br />Like C, C++, every C# program contain ‘Main’ method. <br />Like C++, both single line and multilane comments supports.<br />C# builds on the lessons learned from C (High Performance), C++ (Object Oriented Structure), Java (Security) and Visual Basic (Rapid Development). <br />
  6. 6. First C# Program<br />A simple class that writes a message to screen in file First.cs<br />using System;<br />namespace MyOrg.MyDep.MyApp<br /> {<br />class MyFirstClass <br /> {<br /> public static void Main()<br /> {<br /> Console.WriteLine(“C# is neither C++ nor Java”);<br /> Console.WriteLine(“C# is C Sharp”);<br /> Console.ReadLine();<br /> return;<br /> }<br /> }}<br />C:> csc First.cs //To compile the program. <br />Format of method definition in C# are: <br /> [Modifier] ret_type MethodName(Parameters)<br />
  7. 7. C# Basics<br />The C# compiler requires that any variable be initialized with some starting value before you refer that variable in an operation.<br />C# has two methods for ensuring the variables are initialized before use:<br />Variables those are fields of a class or struct, if not initialized explicitly, are by default zeroed out when they are created. <br />Variables local to method must be explicitly initialized before use them. <br />Let us look at one more different between C++ and C#. <br />MyClass myObj; //In C++ it will create an instance of class on stack. <br /> But in C#, It will just create a reference to MyClass but not initialized to any value. So using myObj without initializing causes error. <br />Instantiating an object in C# requires new keyword. <br />MyClass myObj = new MyClass(); //Now you can use it. <br />
  8. 8. Constants in C#<br />In C# you can use constants to declare local variable and fields. <br />Unlike C++, you can’t declare constants for pointers, methods, and parameters to methods, etc., <br />Constants have the following characteristics: <br />They must be initialized when they are declared and once value is assigned it can’t be overwritten. <br />The value of the constant must be computable at compile time. So runtime you can’t assign value for constant. <br />Constants are always implicitly static. <br />
  9. 9. Data Types in C#<br />C# distinguishes between two categories of data types: <br />Value Types: These types stores its value directly into variable. Value types are stored in stack. <br />int x, y; //Two object of type int created. <br />Reference Types: These types stores the reference to the value. These types are stored in managed heap. <br />Eg: MyClass obj1, obj2;<br /> obj1 = new MyClass();<br /> obj2 = obj1; //Only one instance is created and both are //pointing to same object. <br />In C#, all the primitive data types are value types where as class types are reference types. <br />If you want to declare your own types as value type you should declare it as struct. <br />
  10. 10. Data Types in C#<br />C# has defined 15 predefined types, 13 are primitive types and 2 (object and string) are reference types.<br />All types implicitly derived from the System.Object class. <br />This type implements number of general purpose methods, includes, Equals(), GetHashCode(), GetType() and ToString(). <br />The basic predefined are recognized by C# are not intrinsic to the language but are part of the .NET Framework. <br />If you declare int in C#, what you are actually declaring is an instance of .NET struct System.Int32. <br />
  11. 11. Types in C#<br />
  12. 12. C# Types<br />
  13. 13. C# Types<br />
  14. 14. C# Statements<br />If Statement :Executes statement based on the value of a Boolean expression.<br />Switch Statement : Based on the value of a variable allows to switch to different cases.<br />Do Loop:The purpose of the do loop is to Execute some code and then examine the condition. If the condition is not satisfied then the execution is stopped.<br />While Loop:Evaluate the condition first and then execute the code if the condition is true.<br />For Loop:Executes the statement based on the condition within the for statement.<br />Foreach Statement:Iterate through the each element of a collection.<br />
  15. 15. Enumerations in C#<br />An enumerationis a user defined integer type. C# enumerations are more powerful then its C++ counterparts. <br />You can declare enum in C# as follow:<br />public enum TimeOfDay {<br /> Morning = 0,<br /> Afternoon = 1,<br /> Evening = 2<br /> }<br />The real power of enum in C# is they are instantiated as a struct derived from the base class System.Enum. You cam use methods on this Enum structure. <br />You can retrieve the string representation of an enum as follow: <br />TimeOfDay time = TimeOfDay.Afternoon;<br /> Console.WriteLine(time.ToString()); It prints Afternoon. <br />You can also obtain an enum value from a string:<br />TimeOfDay time = (TimeOfDay)Enum.Parse(typeof(TimeOfDay), “Afternoon”, true );<br /> Console.WriteLine((int) time);<br />
  16. 16. Namespace in C#<br />Namespace is a logical collection of Classes and their related Functions<br />.NET base classes are grouped into different groups through Namespaces <br />A single C# file can declare several Namespaces<br />The Namespaces are Implicitly public<br />Within a Namespace we can declare another Namespace, Class, Interface, Struct, Enum, Delegates<br />You can alias a namespace with using. <br />A Namespace is referenced in a C# program by the “using” statement.<br />The “System” Namespace is the most frequently used Namespace in .NET programming. <br />
  17. 17. Major Namespaces in .NET<br />System: Includes essential classes and base classes for commonly used data types, events, exceptions.<br />System.Collections: Includes classes & interfaces define collection of objects.<br />System.Data: Includes classes which lets us handle data from data sources.<br />System.Data.SqlClient: Includes classes that support the SQL Server .NET provider<br />System.Diagnostics: Includes classes that allow to debug application and to step through our code<br />System.Drawing: Provides access to drawing methods.<br />System.Globalization: Includes classes that specify culture-related information.<br />System.IO: Includes classes for data access with Files.<br />System.Net: Provides interface to protocols used on the internet.<br />System.Reflection: Includes classes and interfaces that return information about types, method and fields.<br />System.Security: Includes classes to support the structure of CLR security system.<br />System.Threading: Includes classes & interfaces to support multithreaded apps. <br />System.Windows.Forms: Includes classes for creating Windows based forms.<br />System.XML: Includes classes for XML support<br />
  18. 18. C# Compiler Options<br />/t:exe A Console Application <br />/t:library A class library with a manifest. <br />/t:module A component without a manifest. <br />/t:winexe A windows application.<br />/out Allow you to specify the name of the output file. <br />/r or To reference types in assemblies those aren’t /reference referenced by default. <br />Eg: To compile C# file into a .NET DLL <br /> csc /t:library MathLib.cs<br />Reference the Dll to new console client application. <br /> csc MathClient.cs /r:MathLib.dll<br />
  19. 19. Console I/O Formatting<br />Console.WriteLine also allow to display formatted output in way comparables to C’s printf. <br />Parameters are zero based indexed. <br />Console.WriteLine(“{0} plus {1} equals to {3}”, 10, 20, 10+20);<br />You can also specify the width for the value and justify the text within that width. For this the format will be {n, w}. Here n is the parameter index and w is the width. <br /> Console.WriteLine("{0,4}{1,4}", 9999, 22); //right justification. <br /> Console.WriteLine("{0,-4}{1,-4}", 9999, 22); // left justification. <br />Other formatting Options are: <br />C Local Currency Format<br />D Decimal Format<br />E Scientific Exponential format<br />F Fixed Format<br />P Percent Format<br />X Hexadecimal format<br /> Console.WriteLine("{0, 9:C2}+{1, 8:C2}---------{2, 9:C2}",123.45, 22.5, 123.45+22.5);<br />
  20. 20. Using Comments in C#<br />Like C++, you can use signle line commant (//) and multiline comments (/* … */) In C#. <br />In addition to above C# also supports XML documentation comments. <br />These comments are single line comments begins with three slashes (///). <br />Within this comments you can place XML tags containing documentation of the types and type members in your code. <br />The following XML tags are recognized by the compiler. <br /> <c>, <code>, <example>, <exception>, <include>, <list>, <param>, <permission>, <remarks>, <returns>, <see>, <summary>, <value><br />To generate XML Document from the code is <br /> csc /doc:format.xml xmldoc.cs<br />
  21. 21. C# Directives<br />#define & #undef<br />#if, #elif, #else and #endif<br />#warning & #error<br />#region & #endregion<br />#line<br />#pragma<br />
  22. 22. Objects & Types<br />
  23. 23. Objects & Types<br />ClassesandStructsare essentially templates from which you can create Objects.<br />Structs differ from classes in the way that they were stored in memory and accessed. <br />They are differ in some other features also such as structs doesn’t support inheritance while classes supports. <br />Structs looks very similar to classes the main difference is use the keyword structinstead of class to declare them. <br />For both classes and structs you use the keyword new to declare an instance. <br />Studentsobj = new Students(); //For Classes to create objects. <br />StudentsStructobj1 = new StudentsStruct(); //For structs.<br />The data and functions within the class are known as class members. They are also termed as data members and function members. <br />
  24. 24. Class Members<br />Data Members:<br />These are the members that contains the data for the class. They are fields, constants and events. <br />Data members can be either static or instance. <br />Fields are any variable associated with the class. Once you have instantiated class object you can access the filed member using Obj.FieldName syntax. <br />Students obj = new Students();<br /> obj.strName = “Mohan”;<br />Constants also associated with class same way as fields. You can declare constants with const keyword. <br />Events are class members that allow an object to notify a caller when something noteworthy happens. <br />
  25. 25. Class Members<br />Function Members:<br />These members provides the functionality for manipulating the data in the class. They includes methods, properties, constructors, finalizers, operators and indexers.<br />Methods can be either static or instance methods. <br />Properties are set of functions that can be associated from the client in the similar way to the public fields of the class. <br />Constructors are special functions those are called automatically when an object is created. <br />Finalizers are called by CLR that an object is no longer needed. They have same name as class preceded by ‘~’. <br />Operators are used to make some actions on user defined types. <br />Indexers allow your object to be indexed in the same way as array or collections. <br />
  26. 26. Methods in C#<br />In C# every function must be associated with a class or struct. <br />In C# the method looks like below. <br />[modifiers] return_type MethodName([parameters]) {<br /> //Method Body<br /> }<br />Passing parameters to methods either by reference or by value.<br />In C# all the parameters are passed by value unless you explicitly says as reference types. <br />By default simple primitive types are passed by value whereas arrays are passed by reference. <br />Any variable passing by value is the default. However with the help of ref keyword you can force the variable to be passed as reference. <br />You will also need to add ref keyword when you invoke method. <br />If function need to output more then one value, use out keyword. <br />
  27. 27. Properties<br />C# supports method overloading. You simple declare methods with the same name but different numbers or types of parameters. <br />Properties:<br />The idea of property is that it is a method of pair of methods that are dressed to look like a field as far as any client code is concerned. <br />A good example is Hight property of Windows Forms. <br />Compared to fields with the help of properties you can validate input values and make any necessary code execution. <br />Eg: myForm.Height = 400; //Sets hight of window and resizes window. <br />To define properties you can use get and set accessories. <br />If you define only get then it will become read only property. Similarly if you define only set then it will become write only property. <br />C# does allows the set and get accessors to have different access modifiers. Take note one of the accessors must follow the access level of the property. <br />
  28. 28. Constructors<br />You can declare a method that has the same name as the containing class and that doesn’t have any return type. <br />For your class if you not supply any constructor then compiler will provide default constructor. <br />It is a basic constructor it will initialize all the fields by zeroing them out (null reference for reference types, zero for numeric data types and false for bool types).<br />You can also overload the constructors. They follow the same rules as method overloading. <br />It is also possible to specify access specifiers on constructors also.<br />It is also possible to write static no-parameter constructors for a class. Such a constructors will be executed only once.<br />This static constructor is used to initialized static fields or properties. <br />There is no guarantee that when static ctor will be executed. Executes at most once. It will be invoked before your code makes reference to class. <br />
  29. 29. Destructors in C#<br />Destructor is used to free the memory space Instantly.<br />The Destructor implements the statements to be executed during the garbage collection process.<br /> A destructor is a function with the same name as the name of the class but starting with the character ~.<br />A Destructor can't have any modifiers like private, public etc.<br />There is no parameterized destructor in C#. <br />Destructors are invoked automatically and can’t be invoked explicitly. <br />class Complex { public Complex() { // constructor } ~Complex() { //No return type, No Parameters, No Access modifiers<br /> // Destructor }} <br />
  30. 30. C# readonly fields<br />You want a variable whose value shouldn’t be changed but the value is not known until runtime. To address this type of scenarios C# supports readonly fields. <br />The readonly field gives bit more flexible then constants. <br />For readonly fields you can make initial value based on calculations. But constants it is not supported. <br />You can assign a value to readonly filed inside constructors only. <br />It is also possible for readonly filed to be instance rather then static field, having a different value for each instance of a class. <br /><ul><li>If a class contains nothing but static methods and properties the class it self become static.
  31. 31. A static class is functionally the same as creating a class with a private static constructor.
  32. 32. An instance of static class never created. Used to create utility classes. </li></li></ul><li>C# Structures<br />Structs are similar to classes but these are value types. <br />In addition classes provides more functionality then structs but it have performance penalty. <br />For performance reasons prefer to use structs rather then classes. <br />Defining functions for structs is also exactly the same as defining them for classes. <br />Structs are value types not reference types. <br />It means these objects are stored either in the stack or inline (If they are part of another object that is stored in heap). Have same life time restrictions that of simple data types. <br />Structs don’t support implementation inheritance. But supports interface inheritance. <br />Structs can’t contain explicit parameter less constructors. (i.e., compiler always supplies a default no parameter ctor). <br />With a struct you can specify how the fields are laid out in memory. <br />
  33. 33. The Object Class<br />All .NET Classes are ultimately derived from System.Object. <br />Every user defined type can access the public and protected member methods of the Object class. <br />System.Object Methods:<br />ToString()<br />GetHashCode()<br />Equals()<br />GetType()<br />MemberwiseClone()<br />Finalize(); <br />
  34. 34. Inheritance<br />
  35. 35. OOPS Concepts in C#<br />All the Object Oriented Programming languages supports the following four concepts: <br />Encapsulation<br />Inheritance<br />Polymorphism<br />Abstraction<br />C# also supports all these concepts. <br />
  36. 36. Inheritance in C#<br />Inheritance is one of the most important, and most powerful, of the object-oriented programming concepts.<br />Using Inheritance, one class can be derived from another.  The derived class, also known as the child class or subclass, inherits functionality from the base class, also known as the parent class or superclass.<br />When using Inheritance, all of the base class' methods, properties, events, indexers, operators and some internal variables are all automatically provided to every subclass.<br />Using Inheritance, classes become grouped together in a hierarchical tree structure. <br />This reduces maintenance problems, as changes need only to be made in one class, rather than throughout a series of related classes.<br />
  37. 37. Types of Inheritances <br />In Object Oriented Programming Languages there are two distinct types of inheritances is concerned.<br />Implementation Inheritance: <br />A type derives from base type, taking all the base type’s member fields and functions. <br />In this inheritance derived type adopts the base types implementation of each function, unless it is indicted in the definition of the derived type that a function implementation is to be overridden. <br />Interface Inheritance:<br />A type that inherits only the signature of the functions but doesn’t inherit any implementation. <br />Interface inheritance often regarded as providing a contract. By deriving interface a type is guaranteed to provide certain functionality to clients. <br />As we discussed previously structs doesn’t support implementation inheritance but it supports interface inheritance. <br />
  38. 38. Inheritance in C#<br />The following different types of inheritances exists in C#. <br />Single Inheritance: <br /> Here we have single base class that is inherited by the derived class. Here the derived class has all the features of the base class and can add new features or modify existing features. The inheritance also depends on the access specifier that is used at the time of base class inheritance.<br />Multi-level Inheritance:<br />In the multi-level inheritance, here we having a chain of inheritance i.e. the base class A is inherited by derived class B, and it is further inherited by another derived class C. So, the feature we have in base class A, is also there in Derived class B, and all the combination features of class A and class B are there in derived class C.<br />
  39. 39. Inheritance in C#<br /><ul><li>Multiple Inheritance:</li></ul>In C#, we don't have multiple inheritance where one class can inherit two base classes. So, the multiple inheritance can be done by using the concept of interfaces. Here one class can inherit one class and can implements more than one interface. <br /><ul><li>Hybrid Inheritance: </li></ul>The hybrid inheritance can also be done through with the help of interface. Here the derived class cans implements more than two interfaces and only one class.<br />
  40. 40. Implementation Inheritance<br />The below is the syntax to define a class that derived from another class. <br />class MyDerivedClass : MyBaseClass {<br /> }<br />If a class (or struct) also derived from interfaces then list of interfaces are separated by commas. <br />C# supports object keyword, which serves as pseudonym for the System.Object class. <br />class MyClass class MyClass : System.Object class MyClass:object<br />{ { {<br />} } } <br />Equals<br />Equals<br />
  41. 41. Implementation Inheritance<br />By declaring base class function as virtual, you allow the function to be overridden in any derived class. <br />It is also possible to declare property as virtual. <br />In the derived classes the overridden function need to be prefixed with override keyword. <br />You can override a virtual function in a derived class, and when the method is called the appropriate method for the type of object is invoked. <br />Neither member fields nor static functions can be declared as virtual. <br />If the method with same signature is declared in both base and derived classes, but the methods are not declared as virtual and override respectively. Then the derived class version is said to hide the base class version. <br />To hide the base class version of a function with new keyword. <br />
  42. 42. Implementation Inheritance<br />C# has special syntax for calling base versions of any method from <br /> derived class as follow:<br />base.<MethodName>();<br />C# allows both classes and functions to be declared as abstract. <br />An abstract class can’t be instantiated. <br />Abstract function can’t have an implementation and must be overridden in non-abstract derived class. <br />If any class contains an abstract function, then class itself is abstract.<br />abstract class Sensors {<br /> public abstract bool Calibrate(); //abstract method. <br /> } <br /><ul><li>C# allows classes and methods to be declared as sealed.
  43. 43. For the classes, it means you can’t inherit from that class.
  44. 44. In case of methods, you can’t override that method. </li></li></ul><li>Modifiers<br />Visibility Modifiers:<br />
  45. 45. Modifiers<br />Public: 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.<br />Private: 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. <br />
  46. 46. Modifiers<br />Protected: 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. <br />
  47. 47. Modifiers<br />Internal:Internalis 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. <br />
  48. 48. Modifiers<br />Protected Internal:Protected Internalmay 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.<br />
  49. 49. Other Modifiers<br />
  50. 50. Interfaces <br />In general an interface can only contain declaration of methods, properties, indexers and events. <br />You can never instantiate an interface. It only contains signature of its members. <br />An interface has neither constructors nor fields. <br />An interface definition is not allowed to contain operator overloads. <br />It is also not permitted to declare modifiers on the members in an interface definition. <br />Interface members are always public and can’t be declared as virtual or static. <br />Similar to classes interfaces can also supports inheritance. So any class that implemented derived interface must implement all the functions of base interface as well as derived interface.<br />
  51. 51. Polymorphism in C#<br /><ul><li>Polymorphism is nothing but one interface which can be used for more then one method</li></li></ul><li>Function Overloading<br />C# allows us to define multiple functions with the same name differing the number type and order of arguments. It is termed as function overloading. <br />Example is given below: <br />using System;<br />class MyClass {<br /> int num;<br /> public void fun(int a){ Console.WriteLine(“Ist func”); <br /> }<br /> public void fun(int a,float b) { Console.WriteLine(“IInd Func”); <br /> }<br />}<br />Public class Program<br />{<br /> public static void Main() {<br /> MyClass obj=new MyClass();<br /> obj.fun(10);<br /> obj.fun(100,200f); <br /> Console.ReadLine();<br /> }<br />
  52. 52. Function Overriding<br />A derived class can override a base-class member function by supplying a new version of that function with the same signature.<br />Function Overriding can be done with the help of either using Virtual class or by using abstract class.<br />Abstract class can contain only abstract method.<br />We can implement abstract methods only in Derived class not in Base class.<br />Virtual method can run under both class and Structure. <br />
  53. 53. Polymorphism in C#<br />Function Overriding using Virtual Method:<br />using System;<br />class BC <br />{ <br /> public virtual void Display() <br /> { <br /> Console.WriteLine("BC::Display"); <br /> } <br />} <br />class DC : BC <br />{ <br /> public override void Display() <br /> { <br /> Console.WriteLine("DC::Display");<br /> } <br />}<br />class Demo <br /> { <br /> public static void Main()<br /> { <br /> BC b;<br /> b = new DC();<br /> b.Display(); //DC :: Display<br /> } <br />}<br />
  54. 54. Polymorphism in C#<br />Function Overriding using Abstract Class: <br />using System;<br />abstract class BC <br />{ <br /> public abstract void Display(); <br />} <br />class DC : BC <br />{ <br /> public override void Display() <br /> { <br /> System.Console.WriteLine(“abstract1");<br /> } <br />}<br />class DA : BC<br />public override void Display() <br /> { <br /> System.Console.WriteLine(“abstract2");<br /> } <br />}<br />class Demo <br /> { <br /> public static void Main()<br /> { <br /> DC obj=new DC();<br /> DA obj1=new DA();<br /> obj.Display();<br /> obj1.Display();<br /> } <br />}<br />
  55. 55. Arrays & Indexers<br />
  56. 56. Arrays<br />If you want to work with multiple objects of the same type, in C# you can use Collections and Arrays. <br />As per .NET arrays are instances of the predefined class called as System.Array. <br />Arrays will be stored in continuous memory.<br />In .NET arrays are belongs to reference types. <br />Always index starts from zero. <br />C# supports three types of arrays: <br />One Dimensional Arrays<br />Two Dimensional Arrays<br />Jagged Arrays. <br />C# has special notation to declare and use arrays. <br />int[ ] myArray; //Declaring array of integer type. <br /> myArray = new int[4]; //Now allocating the memory for arrays.<br />
  57. 57. Arrays<br />If you want to work with multiple objects of the same type, in C# you can use Collections and Arrays. <br />As per .NET arrays are instances of the predefined class called as System.Array. <br />Arrays will be stored in continuous memory.<br />In .NET arrays are belongs to reference types. <br />You can access array elements with indexers. Starts from zero. <br />C# supports three types of arrays: <br />One Dimensional Arrays<br />Two Dimensional Arrays<br />Jagged Arrays. <br />C# has special notation to declare and use arrays. <br />int [ ] myArray; //Declaring array of integer type. <br /> myArray = new int[4]; //Now allocating the memory for arrays.<br />
  58. 58. Arrays<br />The array elements can be accessed with index values. If you use a wrong indexer value where no elements exists, an exception of type IndexOutOfRangeException is thrown. <br />With the help of Length property of Array class you can find number of elements in the array. <br />for(int i = 0; i < myArray.Length; i++)<br /> Console.WriteLine(myArray[i]);<br />To iterate through all the elements of array instead of for loop you can also use foreach loop. <br /> foreach(int val in myArray)<br /> Console.WriteLine(val);<br />Not only predefined types you can also declare arrays for user defined types. <br />Ordinary arrays are indexed with single integer. Multidimensional arrays are indexed with two or more integers. <br />
  59. 59. Jagged Arrays<br />Multidimensional arrays are declared as follow: <br />int[,] my2DimArray = new int [2,3];<br />With jagged array every row can have different size.Declaring jagged array is shown below:<br /> int[ ][ ] jagged = new int[3][ ];<br /> jagged[0] = new int[2] {1,2};<br /> jagged[1] = new int[4] {3,4,5,6,7,8};<br /> jagged[2] = new int[3] {9, 10, 12};<br />You can access the elements of jagged array with the Length property of Array class. Code is shown below. <br />for(int row=0; row < jagged.Length; row++)<br /> for(int element =0; element< jagged[row].Length; element++)<br /> Console.WriteLine(“Row: {0}, Element: {1}, Value = {2}”, row, element, jagged[row][element]);<br />
  60. 60. Array Class<br />Declaring an array with brackets is C# notation of using the System.Array abstract base class. So the methods are propertied defines in this class are access through every C# array instance.<br />Array class is abstract you can’t directly create instance. But it is possible to create array by using static CreateInstance() method. <br />Array employee = Array.CreateInstance(typeof(Person), 5);<br /><ul><li>The Array class contain the following important properties: </li></ul>Length<br />LongLength<br />Rank<br />Arrays are reference types. To copy array from one object to other Array class implements IClonable interface. This interface defines Clone() method. It creates the shallow copy of array. <br />You can also use Array.Copy() to make shallow copy.<br />
  61. 61. Sorting Arrays<br />The Array class also implements bubble sort for sorting the elements of array. It supports Sort( ) method.<br />Sorting arrays on custom classes that class need to implement IComparable. This interface supports just one method ComareTo(). <br />This ComapreTo() method returns 0 if the objects to compare are equal. A value smaller then 0 if the instance should go before the object from the parameter and a value larger then 0 if the instance should go after the object from the parameter. <br />If you don’t have option to change the class that is used as an element of the array by defining Comparer class that implement IComparer interface you can make custom sort. <br />This interface defines method Compare();<br />Array.Sort(MyClass, MyComparerClass); <br />
  62. 62. Interfaces on Array Class<br />The Array class implements the following interfaces for accessing and enumerating the elements of array. <br />IEnumerable<br />ICollection<br />IList<br />With the help of yield statement you can also create enumerators. <br />yield return returns one element of a collection and moves to next. <br />yield break stops the iteration. <br />A method or property that contains yield statement is also known as iterator block. This block must return IEnumerable interface. This block contains multiple yield return or yield break statements, a return statement is not allowed. <br />
  63. 63. Indexers<br />Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access just as an array. <br />Indexers resemble to properties except that their accessors take parameters. <br />Indexers enable objects to be indexed in a similar manner to arrays.<br />To declare an indexer on a class or struct, use the this keyword <br />Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.<br />Indexers can be overloaded.<br />Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.<br />If you declare more than one indexer in the same class, they must have different signatures. <br />C# does not limit the index type to integer. You can also use strings, etc.,<br />You can also implement indexers on interfaces. <br />
  64. 64. Operators & Casts<br />
  65. 65. Operator Precedence<br />
  66. 66. Some more operators<br />checked & unchecked: If you mark block of code as checked, then CLR will enforce overflow checking and throws OverflowException if an over flow occurs. <br />To suppress overflow checking you can use unchecked. <br />‘is’ operator: The ‘is’ operator allow you to check whether an object is compatible with a specific type.<br />Here compatible means that an object is that type or derived from that type. <br />‘as’ operator: This operator is used to explicit type conversion of reference types. If the types are incompatible, the asoperator returns the null.<br />‘sizeof’ operator: To determine the size required on the stack by a value type. Only use with unsafe code.<br />‘typeof’ operator: It returns a System.Type object. <br />
  67. 67. Working with Nullable Types<br />If you wanted to define the value of the type as undefined. Then you can use nullable types. It have distinct values to your application. <br />Nullable types are declared by appending ? at end of type. int? nAge.<br />Usually when using unary or binary operator with nullable type, the result will be null if one or both of the operands is null. <br />When comparing nullable types, if only one of the operand is null, the comparison always equates to false. <br />Null Coalescing Operator(??): This operator provides a short hand mechanism to cater to the possibility of null values when working with nullable and reference types. <br />This operator is placed between two operands. The Null Coalescing operator evaluates as follows:<br />If the first operand is not null, then the overall expression has the value of the first operand. <br />However if the first operand is null. Then the expression value is second operand. <br />
  68. 68. Type Conversion & Casts<br />Often you need to convert data from one type to another. There will be two conversion mechanisms. <br />Implicit Conversion: Conversion between types normally achieved automatically. (Eg: short to int conversion is implicit conversion). <br />Explicit Conversion: Some of the conversions can’t made implicitly. You should make it explicitly using casts. (Eg: int to short). <br />int nVal = 200; <br /> short n = (short) nVal; //Valid cast the max short hold is 32,767<br />Or short n = checked((short)nVal); //Explicit casting with safety. <br />Using casts you can convert most of the primitive types from one type to other. <br />With explicit casting you can convert nullable types to non nullable types. But if the variable contains null value then InvalidOperationException is thrown. <br />
  69. 69. Boxing and Unboxing <br />Boxing is used to describe the transformation of a value type to a reference type. <br />Object is allocated on heap and values copied into it. <br />Occurs implicitly (Can do explicitly also, but no need)<br />int x = 5; //Creates value type.<br /> object y = x; //Creates a System.Int32 on heap. <br /> x = 10;<br /> Console.Writeline(“x has value : {0}”, x); //boxed and ToString() (10) Console.Writeline(“y has value : {0}”, y); //boxed and ToString() (5) <br />Unboxing creates value types from reference types: <br />int z = (int) y ; //unboxing through explicit casting. <br />You can only unbox a variable that has previously been boxed. <br />Take note, while unboxing the receiving value variable has enough room to store all the bytes in the value being unboxed. Otherwise it will result InvalidCastException is thrown. <br />
  70. 70. The process of Boxing<br />Let us consider an example creating intege type on stack. <br />int nVal = 3500; <br /> string s = nVal.ToString(); //or 3500.ToString(). <br />Here nVal is a value type which is just allocated 4 bytes on the stack.<br />Here the magic is C# will do boxing.<br />Behind the scene C# boxes the integer into an object type so that the ToString() method can be invoked against it.<br />
  71. 71. Comparing Objects for Equality<br />The mechanism of object equality is different on whether you are comparing reference types or value types. <br />Comparing Reference Types for Equality: System.Object defines three different methods for comparing objects for equality: <br />ReferenceEquals()<br />Virtual Equals() <br />Static Equals()<br />Comparison Operator (==)<br />Comparing Value Types for Equality: System.ValueType class has overloaded Equal() method in order to test equality for appropriate value types. <br />Suppose you have two instances sA and sB of your defined structure. If you call sA.Equals(sB) then return value will be true if sA and sB contains the same values in all their fields. <br />
  72. 72. Operator Overloading<br />The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or structures is known as operator overloading.<br />In C#, operator overloading works same way for both structs and classes. <br />C# doesn’t allow you to overload the assignment ‘=‘ operator. <br />In C#, some of the operators need to be overload in pairs they are (‘= =’ & !=), (> & <) and (>= & <=). <br />In C#, a special function called operator function is used for overloading purpose.<br />Operator function can take only value arguments. The ref and out parameters are not allowed as arguments to operator functions.<br />C# requires that all operator overloads be declared as public and static. So they are associated with class or struct not with instances. <br />
  73. 73. Operator Overloading<br />
  74. 74. User defined Casts<br />To make conversion between user defined types or between primitive types and user defined types you can define cast operator<br />This cast operator can be declared either implicit or explicit. <br />The syntax for defining cast is similar to that for overloading operators. Similar to operator overloading casts also must be declared as public and static. <br />Cast from any struct (or primitive type) to objecttype is always available as implicit cast. Because it is cast from derived to base.<br />It is also possible to define cast between two user defined data types. It need to obey the following restrictions. <br />You can’t define cast if one of the type is derived from the other. These type of casts already exists. <br />The cast must be defined inside the source of either source or destination type. <br />
  75. 75. Delegates & Events<br />
  76. 76. Delegates<br />In .NET the concept of function pointers are implemented in the form of delegates.<br />Unlike C function pointers the .NET delegates are type-safe. <br />With the help of delegates you can pass one of the method as a argument to a function call. <br />In creating threads you will pass the method as one of argument. <br />In GUI environment for handling events also you can use it. <br />In .NET Delegates are defined with delegate class. Using the delegates is a two stage process. <br />Define the delegate <br />Create one or more instances of the delegate. <br />Delegates in C# always syntactically take one parameter constructor. The parameter being the method that delegate refers.<br />You can invoke a delegate either by supplying brackets to delegate object on calling Invoke method on it. <br />
  77. 77. Delegates<br />You can apply any of the access modifier to delegate. <br />publicdelegate void MyMethodInvoker(int x); //Also apply private, etc..,<br />An instance of a given delegate can refers to any instance or static method on any object of any type, provided that the signature of method should math the signature of delegate. (So type-safety). <br />Delegates are implemented as classes derived from the class System.MulticastDelegate which itself derived from System.Delegate.<br />Delegate Inference: You can also create a delegate and assigning method to it as follow:<br />MyMethodInvokerobjDelegate = MySquareFunc; //Delegate Inference<br />Anonymous Methods: An anonymous method is a block of code that can be used as the parameter of the delegates instead of method. <br />The syntax for defining delegate with anonymous method doesn’t change. While instantiating a delegate you need to supply code block instead of method name. <br />
  78. 78. Multicast Delegates<br />If you wrap a delegate with more then one method that delegate is called Multicast delegate. <br />If a multi cast delegate is invoked, it will successively call each method in order they are registered with delegate. <br />To make sense the delegate signature should return a void; <br />A multicast delegate is a class derived from System.MulticastDelegate which in tern derived from System.Delegate. <br />Let us define a delegate like below:<br />delegate voidMathOpDelegate(double val);<br /> MathOpDelegate d1 = MathClass.MultiplyByTwo; <br /> MathOpDelegate d2 = MathClass.Square; <br /> MathOpDelegate mathOperations = d1 + d2; <br />If one of the method invoked by a delegate thrown an exception, the complete iteration stops. To address this problem you can get list of member functions supported by multicast delegate and invoke them one by one. <br />
  79. 79. Events<br />Events in the .NET are based on delegate model. <br />The event model in .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event two events are needed. <br /><ul><li>A delegate that identifies the method that provides the response to the event.
  80. 80. A class that holds the event data. (Eg: EventArgs)</li></ul>Events enable a class or object to notify other classes or objects when something of interest occurs. <br />The class that sends the event is called as publisher and the class that receives the event called as subscriber. <br />An event can have multiple subscribers. <br />A subscriber can handle multiple events from multiple publishers.<br />Events that have no subscribers are never called.<br />
  81. 81. Events<br />Inside the .NET framework, the EventHandler is a predefined delegate that specially represents event handler method for an event that does not generate data. Its definition inside .NET Framework as below:<br />public delegate void EventHandler( Object sender, EventArgs e ) <br />If your event does generate data then use EventHandler<TEvtArgs> generic delegate class and you can pass custom event data type as parameter. <br /> public delegate void EventHandler<TEventArgs>( Object sender, TEventArgs e ) where TEventArgs : EventArgs<br />In .NET framework events are based on the EventHandler delegate and the EventArgs base class. <br />public delegate void AlarmEventHandler(object sender, AlarmEventArgs e); <br />These events delegates in the .NET framework has two parameters the source that raised the event and the data that raised the event. <br />Similar to multicast delegates, event handlers can’t return a value always returns void. Because event handlers also wrap up more then one handler. <br />
  82. 82. Strings<br />
  83. 83. Strings<br />Microsoft.NET supports several classes to work with strings. <br />The System.Stringclass is specially designed to store a string and allow large number of operations on a string. <br />If you need to make repeated modifications on a string, then it is better to use System.Text.StringBuilder class. <br />StringBuilderstrMsg = new StringBuilder(“Hello all from VisiTECH”, 150); <br />Normally StringBuilder to perform any manipulation of strings and String to store and display the final result. <br />Some of the features of String class are:<br />You can concatenate a string. <br />Cal also extract a particular character using indexer like syntax. <br />String class can also perform lot of other tasks such as replacing characters, removing white spaces, capitalization, etc.,. <br />
  84. 84. Generics<br />
  85. 85. Generics<br />Generics are similar to C++ templates. Generics has the following features: <br />Type Safety, <br />No boxing and unboxing when using collections for value types. <br />No Downcasts. <br />Generic types can be defined in one language and used from any other .NET languages (Binary code reuse). <br />Reduced Code bloat (typed collections).<br />Instantiated at run-time not compile time. <br />Work for both reference and value types. <br />Complete run-time type information. <br />It is not possible to assign null to generic types. In this case the keyword default can be used. <br />
  86. 86. Generics <br />Type parameter can be applied to <br />Classes<br />Structures<br />Interfaces <br />Delegates<br />You can also apply type parameters to methods also<br />Type parameters can have constraints (See next slide). <br />Some more info on Generics:<br />T.default<br />Null Checks<br />Type Casts<br />
  87. 87. Generic Class Features<br />It is not possible to assign null to generic types. In this case the keyword default can be used. <br />T obj = default(T); //Initializing to default. <br />You can apply constraints on generic types. <br />public MyGenericType<T> where T : IEnumerable { .., } <br />Generics supports some more constraints as follow:<br />where T : struct //This constrain says type T must be value type. <br />where T : class // This constrain says type T must be reference type. <br />where T : Foo //T is required to be derived from base class Foo. <br />where T : new() // Specifies T must have default ctor. Constructor Constraint.<br />where T : V //The type T derived from a generic type V. This constraint // is known as “Naked Type Constraint”.<br />You can also combine multiple constraints:<br />public class MyClass<T>where T : IFoo, new()<br />//Here T implements IFoo and have default constructor. <br />
  88. 88. Generics<br />Inheritance in Generics: A generic type can implement a generic interface. Similarly generic class can be derived from a generic base class provided it must follow the below requirement. <br />Generic type of the interface must be repeated or the type of the base class must be specified. <br />Static Members: Static members of a generic class are only shared with one instantiation of the class. <br />There is separate instance of the static variable exist for each type parameter. <br />Generic Interfaces: Using generics you can define interfaces that defines methods with generic parameters. <br />Generic Methods: Like C++, it is also possible to generic methods. Here generic type is define with method declaration. <br />void Swap<T>(ref T x, ref T y) { …,}<br /> Swap<int>(ref i, ref j); //Invoking a generic method. <br />
  89. 89. Generic Delegates<br />With generic delegates the parameter of the delegate can be defined later. Simple delegate examples is given below: <br />public delegate void Del<T>(T item); <br />public delegateT2 Action<T1, T2>(T1 tVal); <br />Nullable<T>: Suppose if you are instantiated as Nullable<int> x. The variable x can now be used like int and also you can assign null to it.<br />Nullable<int> x; //or int? x; if(x.HasValue)<br /> x = 5; int y = x.Value; <br /> x += 20; x = null;<br />EventHandler<TEventArgs>: With Windows forms, Web Applications delegates many different event handlers are defined. <br />ArraySegment<T>: This structure is used to represent a segment of an array. The offset and count of segment is stored in this structure. <br />Benefit of ArraySegment is you can pass it to method as a argument. <br />Take note, ArraySegment don’t make copy of elements of array. It just refers it.<br />
  90. 90. Collections<br />
  91. 91. Collections<br />In the case of arrays the number of elements of the array are fixed. But in the case of collections the number of elements are dynamic.<br />Some of the collection classes are: List<T>, queues, stacks, linkedlists, and dictionaries. <br />There are two types of collection classes. <br />Collection classes those are stored elements of type Object. <br />Generic Collections. <br />There is also other way to group collection classes. They are grouped into Lists, Collections and Dictionaries based on interfaces implemented by that collection class. <br />
  92. 92. Interfaces in Collections<br />
  93. 93. Lists<br />For dynamic lists, the .NET framework offers the classes ArrayList and List<T> classes. <br />ArrayList is non generic list. It accepts any Object type as its element. <br />ArrayList objList = new ArrayList(); //Initial size is 4 elements. Extends.., <br /> ArrayList objeList = new ArrayList(10); //Initial capacity of 10. <br />The List<T> class implements IList, ICollection and IEnumerable interfaces. This is a generic type of list. <br />List<int> intList = new List<int>(10); <br />Both the list supports Capacity and Count properties. <br />In addition to above properties it supports a lot of methods such as Add, RemoveAt, Insert, RemoveRange, ForEach, Find, FindLast, IndexOf, etc., <br />The ConvertAll() method of List<T> converts collection elements from one type to other. This method uses Converter delegate it is defined like below. <br />public sealed delegateTOutput Converter<TInput, TOutput>(TInput from); <br />You can make collections read only by AsReadOnly method. <br />
  94. 94. Queues<br />A queue is a collection where elements are processed in FIFO. In .NET you have non-generic class Queue and generic class Queue<T> for implementing queues. <br />The Queue class implements the ICollection, IEnumerable & IClonable. <br />Similarly Queue<T> class implements IEnumerable<T> and ICollection.<br />Both the Queue classes not implemented IList interface. Like lists you can’t access the elements with Indexer. Only you can add items at end of queue and get the items from the head of queue. <br />With methods Enqueue(), Dequeue() you can add and get items from queue. <br />Methods in Queues are: Enqueue(), Dequeue(), Peak(), Count, TrimExcess(), Contains(), CopyTo(), ToArray().<br />When creating queues you can use the constructors to specify Capacity of queue. The default constructor creates and empty queue. <br />Similar to List<T> class the capacity is always doubled as required. <br />
  95. 95. Stacks<br />A stack is another container it is very similar to Queues. But the stack is a LIFO container. <br />A non-generic Stack class implements the interface ICollection, IEnumerable and IClonable. <br />Generic stack class Stack<T> implements the interfaces IEnumerable<T>, ICollection and IEnumerable. <br />Members of the Stack and Stack<T> class are: Push(), Pop(), Peek(), Count, Contains(), CopyTo(), ToArray()<br />
  96. 96. Linked Lists<br />In .NET, doubly linked lists are implemented with LinkedList<T> class. There is no similar version for non-generic types. <br />The advantages of linked lists over stacks and queues are items are inserted in the middle of the list. The linked list is very fast. <br />Items stored in LinkedList<T> are of the type LinkedListNode<T>. With this class you can get next and previous items in the list. <br />The properties of LinkedListNode<T> are: List, Next, Previous, Value.<br /> The class LinkedList<T> implements the interfaces: ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable and IDeserializationCallback.<br /> The class LinkedList<T> has the following properties: Count, First, Last, AddAfter(), AddBefore(), AddFirst(), AddLast(), Remove(), RemoveFirst(), Clear(), Contains(), Find(), FindLast(). <br />If you need a sorted list you can use the SortedList<TKey, TVal>. In this class elements sorts based on key. <br />
  97. 97. Dictionaries<br />Dictionaries allows you to access an element based on a key. Dictionaries also knows as hash tables or maps. <br />The main features of Dictionaries is fast lookup based on key. <br />In Dictionaries Keys are transformed into a hash. With the hash a number is created to associate an index with the values. The index that contains link to the value. <br />It is also possible that a single index entry can be associated with multiple values, and the index can be stored as a tree. <br />The .NET framework offers several dictionary classes. The major class is Dictionary<TKey, TValue>. <br />A type that is used as a key in the dictionary must override the method GetHashCode() of the Object class. <br />Other Dictionary classes are Non-generic and Generic are: <br />HashTable, ListDictionary, HybridDictionary, NameValueCollection, <br />Dicrtionary<TKey, TValue>, SortedDicrtionary<TKey, TValue><br />
  98. 98. Dictionaries<br />The implementation of GetHashCode() must satisfy the following requirements: <br />The same object should always return the same value. <br />Different objects can return the same value.<br />It should be execute as quickly as possible. <br />It must not throw exceptions. <br />It should use at least one instance field. <br />The hash code value should be evenly distributed across the entire range of numbers that int can store. <br />At best, the hash code shouldn’t change during the lifetime of object. <br />With the help of MultiDictionary<TKey, TValue> class you can add multiple values to the same key. <br />
  99. 99. Bit Arrays<br />To deal with bit level you can use BitArray class or BitVector32 struct.<br />Here BitArray is resizable. But BitVector32 is stack based so it is faster.<br />BitVector32 contains only 32-bits. It is stored in an integer. <br />BitArray members are: Count, Length, Item, Get(), Set(), SetAll(), Not(), And(), Or(), Xor()<br />BitVector32 members are: Data, Item, CreateMask(), CreateSelection().<br />
  100. 100. Memory Management<br />
  101. 101. Memory Management<br />In .NET Values types memory are allocated on Stack, whereas reference types memory will be allocated on managed heap.<br />Employee emp = new Employee(); <br /><ul><li>For the above allocates 4 bytes of memory on stack to hold reference variable(emp) and the size of Employee will be on managed heap.
  102. 102. When a reference variable goes out of scope, this 4 bytes of memory removed from the stack but the data for the referenced object will remain on the heap until either the program terminates or garbage collector removes from it. </li></ul>Generally garbage collector runs when the .NET runtime determines the garbage collection is required. You can also force to run garbage collector at certain point of code by calling GC.Collect(). <br />The GC class represents the Garbage Collector. <br />
  103. 103. Garbage Collector<br />No longer needed objects are freed by the Garbage Collector. However Garbage collector doesn’t know how to free unmanaged resources such as file handles, network connections, etc., <br />To release these unmanaged resources from your managed class there are two mechanisms exists: <br />Declaring destructor (or finalizer) as a member of your class. <br />Implementing System.IDisposable interface on your class. <br /><ul><li>Destructors: Here destructors are called automatically whenever an object is destroyed by the garbage collector.
  104. 104. So within this destructor you can implement code that frees unmanaged resources and perform general cleanup.
  105. 105. Syntax for destructor is similar to C++. It looks like a method with same names as class but prefixed with tidle(~). It has no return type, and takes no parameters and no access modifiers. </li></li></ul><li>Garbage Collector<br />Recommended alternative to using destructor is using the System.IDisposable interface. This interface defines a pattern that provides a deterministic mechanism for freeing unmanaged resources and avoid GC related problems. <br />The IDisposable interface defines a single method Dispose() which takes no parameters and returns void. Within this method you can implement releasing the unmanaged resources. <br />It provides a mechanism that allows users of a class to control when resources are freed but requires discipline to ensure Dispose() is called. <br />The benefit of IDisposable is that whenever variable goes out of scope its Dispose() method is called automatically. <br />In general it is better to implement destructors as well as IDispose on your types those required explicit releasing of resources. <br />
  106. 106. Implementing IDisposable & Destructor<br />We seen two ways for freeing unmanaged resources used by classes in .NET. Each have their limitations. The best approach is implementing both mechanisms in your class. <br />Within the implementation template you can find that second Dispose method which takes one bool parameter and in this you need to implement all clean up code. <br />This Dispose(bool) method is called by destructor as well as Dispose() method. So all cleanup code at one place. Here the parameter indicates whether this method is invoked destructor or IDisposable.Dispose(). <br />The variable bIsDisposed indicates whether the object has already been disposed or not. (So don’t try to dispose resources more then once). <br />The call GC.SuppressFinalize() method tells the garbage collector that a class no longer needs to have its destructor called. Because your implementation of IDisposable.Dispose() has already done all the cleanup required. <br />
  107. 107. Attributes & Reflection<br />
  108. 108. Reflection<br />Reflection is the ability to inspect and manipulate program elements at runtime. Reflection allow you to <br />Enumerate the members of a type. <br />Instantiate a new object and execute a method on object. <br />Find out information about a type or assembly. <br />Inspect custom attributes applied to a type. <br />Create and compile a new assembly. <br />In .NET you can find reflection functionality in classes System.Type and System.Reflection.Assembly classes. <br />In .NET you can allow you to define custom attributes. Custom attributes is a mechanism that allows you to associate a custom meta data with program elements.<br />This meta data is created at compile time and embedded in assembly.<br />Ex: Define author of a class, when program elements last modified, etc.,<br />
  109. 109. Attributes<br />In addition .NET also allow you to define your own attributes called as custom attributes. These attributes emits metadata in the compiled assembly when they are applied to program elements. <br />With the help of reflection you can read this metadata and make decisions at runtime. <br />To define a custom attribute, define a class and derive it from directly or indirectly from System.Attribute. This attribute class need to specify the following information: <br />The type of program elements to which that attribute can be applied. <br />Whether it is legal to apply attribute more then once to same element.<br />If attribute is applied to class or interface is inherited by derived types.<br />The mandatory and optional parameters that attribute takes. <br />Here simple custom attribute example: <br />[AuthorName(“Vishwa Mohan”)]<br /> public class MyClass { ….}<br />
  110. 110. Attributes<br />You can also combine these value using bitwise OR operator.<br /> [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)]<br />You can also use AttributeTargets.All to indicate that your attribute can be applied to all types of program elements. <br />Normally attribute is applied to program elements. In addition to elements an attribute can be applied to an assembly or module as a whole instead of an element. <br />In this case attribute can be placed anywhere in your source code but needs to be prefixed with assembly or module keyword. <br />Normally you can place in AssemblyInfo.cs file. <br />[assembly:AuthorNameAttribute(“Mohan”)]<br />[module:AuthorNameAttribute(“Mohan”)]<br />The AllowMultiple parameter indicates whether an attribute can be applied more then once to the same item. <br />Similarly the Inherited parameter set to true indicates if this attribute is applied to class or interface will also automatically applied to its derived.<br />
  111. 111. System.Type Class<br />In .NET the System.Type class, which let you access information concerning the definition of any data type. <br />Class System.Type is an abstract base class. Whenever you instantiate a Type object you are actually instantiating a class derived from Type. <br />Base Type class has one derived class corresponding to each actual data type, though in general the derived classes simply provide different overloads for the various Type methods and properties. <br />There are three common ways exists for obtaining Type reference. <br />By using C#, typeof operator. <br />Type t = typeof(double); <br />You can use GetType() method. <br /> double d = 10.0;<br /> Type t = d.GetType(); <br />You can use the static method of the Type class GetType(). <br /> Type t = Type.GetType(“System.Double”); <br />
  112. 112. System.Type Class<br />Some of the properties of Type class are: <br />Name, FullName, NameSpace.<br />BaseType, UnderlyingSystemType. <br />IsAbstract, IsArray, IsClass, IsEnum, IsInterface, IsPointer, IsPrimitive, IsPublic, IsSealed, IsValueType. <br />Most of the methods of System.Type are used to obtain the details of the members of the corresponding data type – the constructor, properties, methods, events and so on. Some of the methods are:<br />GetConstructor(), GetConstructors()<br />GetEvent(), GetEvents()<br />GetField(), GetFields()<br />GetInterface(), GetInterfaces()<br />GetMember, GetMembers()<br />GetMethod(), GetMethods()<br />GetProperty(), GetProperties()<br />
  113. 113. Assembly Class<br />The Assembly class defined in the System.Reflection namespace provides access to the metadata for a given assembly.<br />Assembly class also contain methods to load and execute assembly. <br />Assembly myAssembly = Assembly.Load(“SomeAssemblyName”);<br /> Assembly myAssembly = Assembly.LoadFrom(“C:MyDirrAsemblyname”);<br />To get the details of all types those are defined in assemlby.<br />Type[] myAsmTypes = myAssembly.GetTypes();<br />To find out custom attributes in a given assembly are: <br /> Attributes[] myCustomeAttributes = Attribute.GetCustomAttributes(asmbly);<br /> Attributes[] myCustomeAttributes = Attribute.GetCustomAttributes(asmbly, typeof(MyCustomAttributes));<br />
  114. 114. Errors & Exceptions<br />
  115. 115. Exceptions<br />Like C++ and Java in C# errors hare handled with exceptions. <br />In C# an exception is an object created (or thrown) with a particular error condition occurs. <br />In C# exceptions are defined by classes directly or indirectly derived from System.Exception which itself derived from System.Object. <br />The .NET base class library provides many of the predefined exception classes. In addition you can create your own exceptions also. <br />In generally there is no specific namespace for exceptions. <br />The Exception hierarchy consists of two important classes: <br />System.SystemException: This class is for exceptions that are usually thrown by .NET runtime (Eg: StackOverflowException). <br />System.ApplicationException: User defined exceptions should be derived from this class.<br />In C# to handle error conditions normally divide your program into blocks of three different types named as try, catch and finally. <br />Exceptions can also thrown by catch and finally blocks also. <br />
  116. 116. Exceptions<br />Some of the properties of System.Exception class are:<br /><ul><li>Data: It provides you the ability to add Key/value statements to the exception that can be used to supply extra information about the exception.
  117. 117. HelpLink: It is a link to help file to provide more information about exception.
  118. 118. InnerException: If the exception was thrown inside a catch block, then itcontains the exception object that sent to the code into that catch block.
  119. 119. Message: It is a text describe the error condition.
  120. 120. Souces:Name of the application or object that causes the exception.
  121. 121. StackTrace:Provides the details of the method calls on the stack.
  122. 122. TargetSite:This is .NET Reflection object that describes the method that throws the exception.</li></ul>In above properties StackTrace and TargetSite are supplied automatically by runtime. <br />Source will always be filled in by the .NET runtime as the name of the assembly in which the exception was raised. <br />Whereas Data, Message, HelpLink and InnerException must be filled by the code that throws exception. <br />
  123. 123. Exceptions<br />All unhandled exceptions are catched by .NET runtime. The .NET runtime places the entire places another huge try block.<br />You can nest try-catch-finally blocks inside another try block. <br />In .NET it is also possible to define user defined exceptions. These exception classes are derived from ApplicationException class. <br />Defining user defined exceptions doesn’t required to implement any new methods. Only it need to ensure that it will call base class constructor appropriately. <br />
  124. 124. Thank You !<br />You can contact mecherviralavm@gmail.comMobile : 91 9490995632 <br />