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

More Related Content

What's hot

What's hot (20)

OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
C sharp
C sharpC sharp
C sharp
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
 
Tokens in C++
Tokens in C++Tokens in C++
Tokens in C++
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
C# basics
 C# basics C# basics
C# basics
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 

Viewers also liked

OPC Unified Architecture
OPC Unified ArchitectureOPC Unified Architecture
OPC Unified ArchitectureVishwa Mohan
 
OPC UA Connectivity with InduSoft and the OPC Foundation
OPC UA Connectivity with InduSoft and the OPC FoundationOPC UA Connectivity with InduSoft and the OPC Foundation
OPC UA Connectivity with InduSoft and the OPC FoundationAVEVA
 
Manufacturing IoT - OPC UA Information Revolution
Manufacturing IoT - OPC UA Information RevolutionManufacturing IoT - OPC UA Information Revolution
Manufacturing IoT - OPC UA Information RevolutionBill Lydon
 

Viewers also liked (6)

OPC PPT
OPC PPTOPC PPT
OPC PPT
 
Mainframe - OPC
Mainframe -  OPCMainframe -  OPC
Mainframe - OPC
 
Wwf
WwfWwf
Wwf
 
OPC Unified Architecture
OPC Unified ArchitectureOPC Unified Architecture
OPC Unified Architecture
 
OPC UA Connectivity with InduSoft and the OPC Foundation
OPC UA Connectivity with InduSoft and the OPC FoundationOPC UA Connectivity with InduSoft and the OPC Foundation
OPC UA Connectivity with InduSoft and the OPC Foundation
 
Manufacturing IoT - OPC UA Information Revolution
Manufacturing IoT - OPC UA Information RevolutionManufacturing IoT - OPC UA Information Revolution
Manufacturing IoT - OPC UA Information Revolution
 

Similar to CSharp Presentation (20)

Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programming
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
C#unit4
C#unit4C#unit4
C#unit4
 
LEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMTLEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMT
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 
C# note
C# noteC# note
C# note
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
C# Unit 1 notes
C# Unit 1 notesC# Unit 1 notes
C# Unit 1 notes
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
 
c# at f#
c# at f#c# at f#
c# at f#
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 

More from Vishwa Mohan (13)

jQuery
jQueryjQuery
jQuery
 
WPF
WPFWPF
WPF
 
Da package usersguide
Da package usersguideDa package usersguide
Da package usersguide
 
Dareadme
DareadmeDareadme
Dareadme
 
Linq
LinqLinq
Linq
 
Uml
UmlUml
Uml
 
Xml
XmlXml
Xml
 
Real Time Systems &amp; RTOS
Real Time Systems &amp; RTOSReal Time Systems &amp; RTOS
Real Time Systems &amp; RTOS
 
Embedded Linux
Embedded LinuxEmbedded Linux
Embedded Linux
 
Introduction To Embedded Systems
Introduction To Embedded SystemsIntroduction To Embedded Systems
Introduction To Embedded Systems
 
Microsoft.Net
Microsoft.NetMicrosoft.Net
Microsoft.Net
 
Zig Bee
Zig BeeZig Bee
Zig Bee
 
WCF
WCFWCF
WCF
 

Recently uploaded

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 

CSharp Presentation

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