You are on page 1of 27


[] 1. Constructor is a method in a class which gets executed when an object of the class is instantiated. 2. A constructor will have exact same name as the class and it does not have any return type. 3. C# supports overloading of constructors – We can have constructors with different set of parameters. 4. We can call one constructor from another constructor using initializers [this & base] This is known as constructor chaining. public class mySampleClass Execution Sequence: { public mySampleClass() : this(10) 1. public mySampleClass(int Age); { } 2. public mySampleClass(); public mySampleClass(int Age) { } } mySampleClass obj = new mySampleClass(); Here, the code of mySampleClass(int Age) will be executed before the code of mySampleClass(). Execution Sequence: 5. Constructors in Inheritance
1. myDerivedClass obj = new my DerviedClass(); a. public myBaseClass(); b. public myDerivedClass(); 2. myDerivedClass obj = new myDerivedClass(15); a. public myBaseClass(15) b. public myDerivedClass(15);

public class myBaseClass { public myBaseClass() { } public myBaseClass(int Age) { } } Public class myDerivedClass : myBaseClass ( public myDerivedClass() { } Public myDerivedClass(int Age) : base(Age) { } ) 6. Private Constructors a. Constructors can have “private” access specifiers.


b. The class which has only private constructors can neither be instantiated nor be inherited. c. If we have only static members in a class and we don’t need to instantiat e, then we can have private constructors. d. Public constructor can access the private constructor with in the class. public class myClass { Private myClass() { } public myClass(int Age) : this() { } } 7. Static Constructors a. There can be only one static constructor in a class. b. Static constructors should be without parameters. c. Static constructors do not have access specifiers. d. Static constructors can have only static members. Note: The call to the static member is made by the CLR, not by the object created, so we do not need to have an access specifier & parameters. public class myClass { static myClass() { } Public myClass() { } }

1. A Destructor is a special member function of a class that is executed whenever an object of the class goes out of the scope. 2. A destructor have the exact same name as the class, prefixed with ‘ ~ ‘ symbol. 3. It can neither return a value not take any parameters. 4. Destructors cannot be inherited or overloaded. 5. Destructor can be very useful for releasing resources before coming out the program, like closing files, releasing memories etc.


using System; namespace LineApplication { class Line { private double length; // Length of a line public Line() // constructor { Console.WriteLine("Object is being created"); } ~Line() //destructor { Console.WriteLine("Object is being deleted"); } public void setLength( double len ) { length = len; } public double getLength() { return length; } static void Main(string[] args) { Line line = new Line(); // set line length line.setLength(6.0); Console.WriteLine("Length of line : {0}", line.getLength()); } } }
Output Object is being created Length of line : 6 Object is being deleted

Static Variable
1. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.


2. The keyword static implies that only one instance of the member exists for a class. using System; namespace StaticVarApplication { class StaticVar { public static int num; public void count() { num++; } public int getNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s1 = new StaticVar(); StaticVar s2 = new StaticVar(); s1.count(); s1.count(); s1.count(); s2.count(); s2.count(); s2.count(); Console.WriteLine("Variable num for s1: {0}", s1.getNum()); Console.WriteLine("Variable num for s2: {0}", s2.getNum()); Console.ReadKey(); } } } Output Variable num for s1: 6 Variable num for s2: 6


Static Methods
1. Static methods can access only static variables. 2. The static functions exist even before the object is created. using System; namespace StaticVarApplication { class StaticVar { public static int num; public void count() { num++; } public static int getNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s = new StaticVar(); s.count(); s.count(); s.count(); Console.WriteLine("Variable num: {0}", StaticVar.getNum()); Console.ReadKey(); } } } Output Variable num: 3


1. Delegates are reference type variables which hold the method reference. 2. Delegates are especially used for implementing events and call-back methods. It improves performance. 3. All delegates are derived from System.Delegate class. Declaring Delegates 1. The signature of the delegate should match the signature of the method it refers. Syntax: delegate <Return Type> <Delegate Name> (<Parameter List>) Ex: public delegate int myDelegate(string s)
If we are referring to the method with two int parameters and int return type, the delegate which we are declaring should be in the same format. This is why it is referred to as type safe function pointer.

Instantiating Delegate 1. Delegate object should be created using the new keyword. 2. While instantiating the delegate, the parameter should be the method name without parameters. Ex: myDelegate obj = new myDelegate(AddNum); Multicasting Delegates 1. Multi-cast delegate is a delegate which holds more than one method reference. 2. Delegate objects can be composed or decomposed using the ‘+’ or ‘-‘ operators. 3. We can invoke a list of methods, when a multi-cast delegate is invoked. Example using System; namespace Samples { delegate int myDelegate(int n); class Program { static void Main(string[] args) { myClass m = new myClass(); myDelegate md = new myDelegate(m.AddNum); myDelegate md1 = new myDelegate(m.MultipyNum); Console.WriteLine(md(10)); Console.WriteLine(md1(10));


Console.ReadLine(); } } public class myClass { public int AddNum(int a) { return 2 + a; } public int MultipyNum(int b) { return 2 * b; } } }

ValueType vs ReferenceType

S.No. Value Type 1 Stores the actual data 2 Value type has its own copy of data.


4 5

Value type should always contain a value. [ie.., default value is 0. It cannot be null] Ex : int a; By default the value will be 0. Stored on a stack Retains the original value, even if we change the value of the other value type variable. using System; class TestValueTypes { public static void Main() { int a = 5; int b; b = a; Console.WriteLine("a = " + a + "\nb = " + b);

Reference Type Stores the reference to the data Reference type has a reference to the data and several variables can reference the same data. It can be null. Ex : MyClass obj; By default, obj is null. Allocated on a heap. When we alter the value for one of them, the other will get the same value using System; public class Cat { private int age; public void SetAge(int years) { age = years; } public int GetAge() {


a++; Console.WriteLine("We have now increased a with 1"); Console.WriteLine("a = " + a + "\nb = " + b); } } Output: a=5 b=5 We have now increased a with 1 a=6 b=5

return age; } } public class RefTest { public static void Main() { Cat miranda = new Cat(); miranda.SetAge(6); Cat caesar = miranda; //caesar now equals miranda Console.WriteLine("Caesar: " + caesar.GetAge()); Console.WriteLine("Miranda: " + miranda.GetAge()); miranda.SetAge(10); //change Miranda's age, what happen to Caesar now? Console.WriteLine("Caesar: " + caesar.GetAge()); Console.WriteLine("Miranda: " + miranda.GetAge()); Console.WriteLine(caesar == miranda); } } Output: Caesar: 6 Miranda: 6 Caesar: 10 Miranda: 10


Boxing and Unboxing
When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type it is called unboxing. Object obj; Obj = 100; // this is boxing.

1. 2. An array is a collection of data of same type. Syntax : datatype[ ] arrayname; Ex : int [ ] arr;

Concepts on array 1. 2. 3. 4. 5. Multi-dimensional array Jagged array Passing arrays to functions Param arrays The Array class

Multi-dimensional array Syntax : int [ , ] mulArr ; Ex : int [ , ] a = new int [3,2] { (7,4) , (3,6) , (1,4) };

Jagged array Syntax : int [ ] [ ] jagArr; Int [ ] [ ] scores = new int [ 2 ] [ ] { new int [ ] { 92,93,94 }, new int [ ] { 85,66,87,88 } }; Where, scores is an array of two arrays of integers -- scores[0] is an array of 3 integers and scores[1] is an array of 4 integers. Passing array to functions We can pass an array as a function argument. Ex : public double getAverage(int [ ] arr, string a) { } Public void Process( )

10 { int [ ] a = new int [ ] { 1000, 200,358 } ; double avg = getAverage ( a , “Sample”); } Param Arrays (Parameter Arrays) If the number of arguments passed is not known while declaring a method, then “Param Arrays” can be used.

Ex : using System; namespace ParamArrayTest { class myClass { public int getSum(Params int [ ] arr) { int sum = 0; foreach ( int i in arr ) sum += i; return sum; } } class TestClass { public static void main(string [ ] args) { myClass obj = new myClass(); int a = obj.getSum( 10, 20 ,30, 40, 30 ); } } } The Array Class 1. Array class is the base class for all the arrays. 2. It is defined in the System namespace. 3. Array class provides various properties and methods to work with arrays. Properties 1. IsFixedSize 2. IsReadOnly 3. Length


4. LongLength 5. Rank Methods 1. Clear 2. Copy(Array, Array, Int32) 3. CopyTo(Array, Int32) 4. GetLength() 5. GetLongLength() 6. GetLowerBound() 7. GetUpperBound() Ex : int[] list = { 34, 72, 13, 44, 25, 30, 10 }; int[] temp = list; Array.Reverse(temp); Array.Sort(list);

8. GetType() 9. GetValue(Int32) 10. IndexOf(Array, Object) 11. Reverse(Array) 12. SetValue(Object, Int32) 13. Sort(Array) 14. ToString()

1. Structures are used to hold related data of various data types in a single variable. 2. Structures of value type whereas classes are reference type. 3. Structures do not support inheritance. using System; struct Books { private string title; private string author; private string subject; private int book_id; public void getValues(string t, string a, string s, int id) { title = t; author = a; subject = s; book_id = id; } public void display() {


Console.WriteLine("Title : {0}", title); Console.WriteLine("Author : {0}", author); Console.WriteLine("Subject : {0}", subject); Console.WriteLine("Book_id :{0}", book_id); } }; public class testStructure { public static void Main(string[] args) { Books Book1 = new Books(); /* Declare Book1 of type Book */ Books Book2 = new Books(); /* Declare Book2 of type Book */ /* book 1 specification */ Book1.getValues("C Programming", "Nuha Ali", "C Programming Tutorial",6495407); /* book 2 specification */ Book2.getValues("Telecom Billing", "Zara Ali", "Telecom Billing Tutorial", 6495700); /* print Book1 info */ Book1.display(); /* print Book2 info */ Book2.display(); Console.ReadKey(); } }

1. An Enumeration is a set of named integer constants. 2. Syntax : enum <enum-name> { <enum-list> }; 3. Ex : enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; using System;


namespace EnumApplication { class EnumProgram { enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat }; static void Main(string[] args) { int WeekdayStart = (int)Days.Mon; int WeekdayEnd = (int)Days.Fri; Console.WriteLine("Monday: {0}", WeekdayStart); Console.WriteLine("Friday: {0}", WeekdayEnd); Console.ReadKey(); } } }

1. Encapsulation is a process of enclosing one or more items in a physical and logical package. 2. In oops, encapsulation prevents access to implementation details. 3. Encapsulation is implemented using access specifiers.

Access Specifiers
1. An access specifier defines the scope and visibility of the class member. a. Public Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class. b. Private Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. c. Protected Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. d. Internal Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In


other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined. e. Protected Internal The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance. Note : 1. Default access specifiers are Internal & Private. That is, if not mentioned then the default access specifier for a class is “Internal”. Default access specifier for class members are “Private”. 2. class myClass { }  internal class myClass { } int i;  private int i; void method1( ) { }  private void method1( ) { }

Inheritance: It is the capability of one class to inherit properties from another class. Base Class: It is the class whose properties are inherited by another class. It is also called Super Class. Derived Class: It is the class that inherit properties from base class(es).It is also called Sub Class.

Multiple Inheritance is not allowed in c#. However, it can be achieved through Interfaces.


1. It is the ability of a class to define methods with same name and different implementations. 2. Types : a. Static Polymorphism/Compile-time polymorphism/Early Binding i. Method Overloading ii. Operator Overloading b. Dynamic Polymorphism/Run-time polymorphism/Late Binding
When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. To change the data and behavior of a base class, we have two choices: i. we can replace the base member with a new derived member, or ii. we can override a virtual base member.

Static Polymorphism Method Overloading 1. We can have multiple definitions for the same method in the same scope. 2. The definition of the method must differ from each other by the datatypes/number of arguments in the parameter list. 3. We cannot overload a method declaration that differ only by return type. Class MethodOverloadingEx { public void print ( int a ) { } public int print ( string str ) { } public void print ( double b ) { } public static void main(stirng [] args) { print(100); int x = print(“Test”); print(200.10); } } Operator Overloading 1. We can redefine or overload most of the built-in operators in c#. 2. Overloaded operators are methods with special names having the keyword “operator” followed by the symbol for the operator being defined. 3. Binary & comparison operators can be overloaded. 4. The assignment operators and “=” cannot be overloaded.


Ex: using System; namespace OperatorOvlApplication { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public double getVolume() { return length * breadth * height; } public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } // Overload + operator to add two Box objects. public static Box operator+ (Box b, Box c) { Box box = new Box(); box.length = b.length + c.length; box.breadth = b.breadth + c.breadth; box.height = b.height + c.height; return box; } public static bool operator <(Box lhs, Box rhs) { bool status = false; if (lhs.length < rhs.length && lhs.height < rhs.height && lhs.breadth < rhs.breadth) {


status = true; } return status; } } class Tester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); // Declare Box2 of type Box Box Box3 = new Box(); // Declare Box3 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); Console.WriteLine("Volume of Box1 : {0}", volume); // volume of box 2 volume = Box2.getVolume(); Console.WriteLine("Volume of Box2 : {0}", volume); // Add two object as follows: Box3 = Box1 + Box2; // volume of box 3 volume = Box3.getVolume(); Console.WriteLine("Volume of Box3 : {0}", volume); if (Box1 < Box2) Console.WriteLine("Box1 is less than Box2"); else Console.WriteLine("Box1 is not less than Box2");



} } } Output Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400 Dynamic Polymorphism Using new Keyword 1. If a base class defines a method, field, or property, the new keyword is used to create a new definition of that method, field, or property on a derived class. 2. When the new keyword is used, the new class members are called instead of the base class members. Those base class members are called hidden members. 3. Hidden class members can still be called if an instance of the derived class is cast to an instance of the base class. public class BaseClass { public void DoWork() { } public int WorkField; public int WorkProperty { get { return 0; } } } public class DerivedClass : BaseClass { public new void DoWork() { } public new int WorkField; public new int WorkProperty { get { return 0; } } } DerivedClass B = new DerivedClass(); B.DoWork(); // Calls the new method.


BaseClass A = (BaseClass)B; A.DoWork(); // Calls the old method. Using Override keyword/Overriding 1. In order for an instance of a derived class to completely take over a class member from a base class, the base class has to declare that member as virtual. 2. This is accomplished by adding the virtual keyword before the return type of the member. 3. A derived class then has the option of using the override keyword, instead of new, to replace the base class implementation with its own. 4. Fields cannot be virtual; only methods, properties, events and indexers can be virtual. public class BaseClass { public virtual void DoWork() { } public virtual int WorkProperty { get { return 0; } } } public class DerivedClass : BaseClass { public override void DoWork() { } public override int WorkProperty { get { return 0; } } } DerivedClass B = new DerivedClass(); B.DoWork(); // Calls the new method. BaseClass A = (BaseClass)B; A.DoWork(); // Also calls the new method.

Abstract Class
1. Abstract keyword is used to create classes and class members that are incomplete and must be implemented in a derived class. 2. An abstract class cannot be instantiated. 3. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract


class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. 4. Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. 5. Derived classes of the abstract class must implement all abstract methods. Ex 1 : public abstract class A { public abstract void DoWork(int i); } Ex 2 :
i. If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. j. A class inheriting an abstract method cannot access the original implementation of the method—in the below example, DoWork on class F cannot call DoWork on class D. k. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

// compile with: /target:library public class D { public virtual void DoWork(int i) { // Original implementation. } } public abstract class E : D { public abstract override void DoWork(int i); } public class F : E { public override void DoWork(int i) { // New implementation. } }

Sealed Class


1. The Sealed keyword is used to prevent the inheritance of a class. 2. A sealed class cannot be used as a base class. So, it cannot be an abstract class. 3. Because sealed class can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Ex 1 : public sealed class D { // Class members here. } Ex 2 : A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. j. This negates the virtual aspect of the member for any further derived class. k. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration

public class D : C { public sealed override void DoWork() { } }

1. 2. 3. 4. 5. 6. Interfaces contain only the declaration of the members. Any class or struct that implements the interface must implement all its members. An interface cannot be instantiated directly. Interfaces can contain methods, properties, events & indexers. A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces. namespace InterfaceApplication { public interface ITransactions { // interface members void showTransaction(); double getAmount(); }


public class Transaction : ITransactions { private string tCode; private string date; private double amount; public Transaction() { tCode = " "; date = " "; amount = 0.0; } public Transaction(string c, string d, double a) { tCode = c; date = d; amount = a; } public double getAmount() { return amount; } public void showTransaction() { Console.WriteLine("Transaction: {0}", tCode); Console.WriteLine("Date: {0}", date); Console.WriteLine("Amount: {0}", getAmount()); } } class Tester { static void Main(string[] args) { Transaction t1 = new Transaction("001", "8/10/2012", 78900.00); Transaction t2 = new Transaction("002", "9/10/2012", 451900.00); t1.showTransaction(); t2.showTransaction(); Console.ReadKey(); } } } Output Transaction: 001 Date: 8/10/2012


Amount: 78900 Transaction: 002 Date: 9/10/2012 Amount: 451900

Abstract Class Vs Interface
Feature Multiple inheritance Default Implementation Interface A class may inherit several interfaces.
An interface cannot provide any code, just the signature.

Abstract Class A class may inherit only one abstract class.
An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modifiers

Fields and Constants Adding functionality (Versioning)

An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public No fields can be defined in interfaces If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

An abstract class can contain access modifiers for the subs, functions, properties An abstract class can have fields and constrants defined If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.


1. Namespace is used to declare a scope. 2. Within a namespace we can declare one or more, a. Another Namespace b. Class c. Interface d. Struct e. Enum f. delegate

namespace SampleNamespace { class SampleClass{} interface SampleInterface{} struct SampleStruct{} enum SampleEnum{a,b} delegate void SampleDelegate(int i); namespace SampleNamespace.Nested { class SampleClass2{} } }

3. The compiler adds a default namespace, whether or not we explicitly declare a namespace. This unnamed namespace is called global namespace. 4. Namespaces implicitly have public access and this is not modifiable. 5. It is possible to define a namespace in two or more declarations. For example, the following code is valid. namespace MyCompany.Proj1 { class MyClass { } } namespace MyCompany.Proj1 { class MyClass1 { } }

1. An assembly is a file that is automatically generated by the compiler upon successful compilation of every .Net application. 2. It can be either .dll(Dynamic Link Library) or .exe(Executable file). a. .exe files have main entry point. [known as Application Assemblies] b. .dll files do not have a main entry point. [known as Libraries] 3. It is generated only once for an application and upon each subsequent compilation the assembly gets updated. 4. An assembly contains IL (Intermediate Language) code, metadata and a special file called Manifest. 5. Metadata enumerates the features of every type in the assembly.


6. Manifest contains the information about the current version of the assembly and other related information. 7. The IL code generated by the compiler can be viewed with the help of the utility ILDASM.exe (Intermediate Language Disassembler). HelloLibrary.cs namespace Microsoft.CSharp.Introduction { public class HelloMessage { public string Message { get { return "hello, world"; } } } } csc /target:library HelloLibrary.cs It produces a class library named HelloLibrary.dll HelloApp.cs using Microsoft.CSharp.Introduction; class HelloApp { static void Main() { HelloMessage m = new HelloMessage(); System.Console.WriteLine(m.Message); } }

csc /reference:HelloLibrary.dll HelloApp.cs It produces an application executable file named HelloApp.exe.

Types of assembly 1. Private Assembly 2. Shared Assembly (also known as public assembly) 3. Satellite Assembly 1. Private Assembly: It is used only by the single application and is stored in the application's installation directory . Creating a private assembly Open visual studio  Create Project  Class Library namespace PrivateAssembly { public class Class1 { public string display() {


return "This is from Private Assembly"; } } }

Building this application 1. If we build this application in Debug mode, then PrivateAssembly.dll will be in Debug folder of bin folder. 2. If we build this application in release mode, then the PrivateAssembly.dll will be in release folder of bin folder. Now you can create a client application to use the above created private assembly by referencing it, using “AddReference”. 2. Shared Assembly 1. A shared assembly is an assembly contains version. 2. It is stored in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by the .NET runtime. It is located at C:\Windows\Assembly OR C:\Winnt\Assembly. 3. A shared assembly may be used by many applications. 4. To make an assembly a shared assembly, ie., in order to share an assembly with many applications, it must have a strong name. 5. A strong name assembly is an assembly that has its own identity, through its version and uniqueness.


Converting a private assembly to a shared assembly 1. Creating Strong Name Key a. “sn.exe” is a tool used to create a cryptographic key pair. b. The generated key pair can be stored in a file or in the machine’s Cryptographic Service Provider(CSP). c. The following command in the .Net command interpreter, creates the strong name key file called “samplekey.snk”, sn –k C:\samplekey.snk 2. Creating Strongly Named Assembly a. Go to the assemblyinfo.cs and make the following changes, using System.Reflection [assembly: assemblykeyfileattribute(“C:\samplekey.snk”)] namespace StrongName { public class SampleClass { } } If the key is stored in a file, then we can use the attribute “AssemblyKeyFileAttribute” as above. If the key is in the CSP, we should use the attribute “AssemblyKeyNameAttribute”. 3. Installing the Shared Assembly in GAC a. To install in GAC, type the following command in .Net command interpreter, gacutil /i SampleClass.dll b. To uninstall a shared assembly from the GAC, type the following, gacutil /u SampleClass.dll