You are on page 1of 47

C Sharp Programming Day 2

Day 2
Interface Properties Indexers Collections Introduction to Preprocessor directive Compiler Switches Assemblies
Private Public Versioning

Copyright 2005, 2 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Interface
Definition: An interface is a collection of abstract methods that is used to define the functionality of an application. The methods of an interface are defined in the classes or structs that implement the interface.

Copyright 2005, 3 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Interface
Uses of Interface: Interfaces can be used as a means to provide some inheritance features with structures. Multiple interfaces can be implemented with a class, thus gaining functionality one cant obtain with an abstract class.

Copyright 2005, 4 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Interface
Syntax: Interface_ Modifer interface Interface_ identifier : base_interface E.g.: public interface ITextBox : IControl { . } // interface body

The interface body contains the members of the interface. An interface contains the members that are inherited from its base interfaces and its own members.

Copyright 2005, 5 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Interface
Members of an interface:
Methods Properties Events

An interface modifier cannot be specified for an interface member. All the interface members are public by default. This is because any class or struct in the program can access the interface members. Interface members are defined in a class. An interface cannot contain constants, fields and operators. An interface cannot contain constructors and destructors.

Copyright 2005, 6 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Implementing an interface in a class


interface IShape { // interface method declaration void Draw(); }

class Circle : IShape { void Draw() { // interface method definition // method definition

. } }

Interface
Copyright 2005, 7 Infosys Technologies Ltd

Interface

ER/CORP/CRS/LA30FC/003 Version no: 2.0

E.g.: interface ICntrl { void Draw(); } interface ITxtBox : ICntrl { void SetText( string text); } class TxtBox : ITxtBox { void ICntrl.Draw() { } // method definition // method definition // method declaration // interface method declaration

void ITxtBox.SetText() { } }

If an inherited interface is implemented in a class, the class implicitly implements the base interface members of the inherited interface.

Copyright 2005, 8 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Explicit Interface Implementation


Explicit interface implementation is used to remove ambiguity Handles name collisions Explicit interface implementations cant be declared with abstract , virtual, override or new modifiers No access modifier

Copyright 2005, 9 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Explicit Interface Implementation


public interface IDelete { void Delete(); // interface method declaration }

public interface ITransact { void Delete(); // interface method declaration }

class TextBox : IDelete, ITransact { void IDelete.Delete() { ... } // method definition void ITransact.Delete() { ... } // method definition }

Copyright 2005, 10 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Explicit Interface Implementation


Explicit interface member implementations take precedence over other members of the class when determining the class member that will be mapped as the implementation of an interface member. interface IAdd { void } class Calculate { void IAdd.Add ( int a, int b) { } public void Add() { } }
Copyright 2005, 11 Infosys Technologies Ltd ER/CORP/CRS/LA30FC/003 Version no: 2.0

Add ( int a, int b);

// method body

// method body

Classes Versus Interfaces


An interface is like a pure abstract class. An interface differs from a class in a number of ways:
An interface does not provide any implementation code. This will be done by the classes that implement the interface. An interface is said to provide a specification or guideline for what will be happening, but not the details. All the members of the interface are assumed to be public. Interfaces contain only methods, properties, events and indexers. They do not contain data members, constructors, or destructors. They cannot contain any static members.

Copyright 2005, 12 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Which statement gives a compilation error in the code snippet listed below: interface IAdd { void } Add ( int a, int b);

class Calculate{ public void IAdd.Add ( int a, int b) { . } } // method body

Copyright 2005, 13 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Spot the error in the code snippet listed below: interface IAdd { void } Add ( int a, int b); // method declaration

class Calculate : IAdd { void Add ( int a, float b) { // method definition . } } // method body

Copyright 2005, 14 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Properties
C# provides a concept called properties to enable to create object oriented fields within the classes. Properties use the keywords get and set to get the values from the variables and set the values in the variables.

// property.cs Using properties //------------------------------------------------------------------

class point { int iPointx; // iPointx is private int iPointy; // iPointy is private public int iPointx1 { get { return iPointx; }

Copyright 2005, 15 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

set { iPointx = value; } } public int iPointy1 { get { return iPointy; } set { iPointy = value; } } }

Copyright 2005, 16 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Class MyApp { public static void Main() { point starting = new point(); point ending = new point(); starting.iPointx1 = 1; starting.iPointy1 = 4; ending.iPointx1 = 10; ending.iPointy1 = 11; System.Console.WriteLine(Point 1: {0},{1}), starting.iPointx1, starting.iPointy1); System.Console.WriteLine(Point 2: {0},{1}), ending.iPointx1, ending.iPointy1); } }

Copyright 2005, 17 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Properties - Demo

Properties (Class1.cs)

Properties (Class2.cs)

Copyright 2005, 18 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Indexers
Enables an object to be indexed in the same way as an array. The signature of indexer is <modifier> <return type> this [argument list] The modifier can be private, public, protected or internal The this is a special keyword in C# to indicate the object of the current class The formal-argument-list specifies the parameters of the indexer. C# do not have the concept of static indexers A base class indexer is inherited to the derived class.

I d x r(Cl

cs)

I d x r(Cl ss2.cs)

I d x r

Copyright 2005, 19 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Indexers & Properties


Indexer Properties

An indexer is identified by its signature. An indexer is always an instance member An indexer is accessed through an element access.

But a property is identified by its name.

property can be static also.

But a property is through a member access

Copyright 2005, 20 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Pre-processing directives
These directives are called preprocessor directives because before compiling the code, the compiler preprocesses the listing and evaluates any preprocessor directives.

Directive

Description

#define, #undef

Defines and undefines conditional symbols


Ind x

#if, #elif, #else, #endif

Conditionally skip sections of code

#error, #warning

Issue errors and warnings

#region, #endregion #line

Delimits / outlines regions Specify line number

Copyright 2005, 21 Infosys Technologies Ltd


Cl

ER/CORP/CRS/LA30FC/003 Version no: 2.0

// preprocess.cs using the preprocessor directives // --------------------------------------------------------#define DEBUG Using System; Using System.IO; Public class ReadingApp { public static void Main(String[] args) { if( args.Length < 1) { Console.WriteLine(Must include file name.); } else {
Copyright 2005, 22 Infosys Technologies Ltd ER/CORP/CRS/LA30FC/003 Version no: 2.0

#if DEBUG Console.WriteLine( ========== DEBUG INFO========== ); for ( int x= 0; x < args.Length ; x++) { Console.WriteLine( Arg[{0}] = {1}, x, args[x]); } Console.WriteLine( =============================== ); #endif string buffer; StreamReader myFile = File.OpenText(args[0]); while ( buffer = myfile.ReadLine()) != null ) { #if DEBUG Console.Write( {0:D3} , buffer.Length); #endif Console.WriteLine(buffer); } myFile.Close(); } } }
Copyright 2005, 23 Infosys Technologies Ltd ER/CORP/CRS/LA30FC/003 Version no: 2.0

Collection
A collection is a specialized class that organizes and exposes a group of objects. Various collection classes are ArrayList, BitArray, HashTable, SortedList, Queue and Stack They are all included in System.Collections namespace Like arrays, members of collections can be accessed by an index. Unlike arrays, collections can be resized dynamically. Collection Classes implement following interfaces IEnumerable - Supports method GetEnumerator () IEnumerator - Supports method MoveNext () and property Current

Copyright 2005, 24 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

ArrayList
System.Collections.ArrayList class allows to dynamically add and remove items from a simple list. The list of objects managed by the Array List is a zero based collection. The items in the list are retrieved by accessing the item index. Methods
Add() Remove() RemoveAt()

Property
Indexer Count
Arr yL st

Copyright 2005, 25 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Hashtable
System.Collections.Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses hashing algorithm to store and index values It makes use of the GetHashCode() method to generate the hashcode Methods
Add() Remove()

Property
Indexer Count

HashTable

Copyright 2005, 26 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

foreach loop
Can be used to loop through in an array or collection in turn. int [] num= {10,20,30,40}; foreach (int i in num) { Console.WriteLine(i); } //Assumes that myList is an ArrayList that contains Strings //and variety of objects of other types foreach (object o in myList) { if(o.GetType() == typeof(string)){ Console.WriteLine(o.ToString()); } }
Copyright 2005, 27 Infosys Technologies Ltd ER/CORP/CRS/LA30FC/003 Version no: 2.0

Compile Switches
-option or /option /doc:file.xml
Used to process documentation comments Are generated after compiling source file and stored in a xml file csc /doc:firstc.xml firstc.cs

/out:filename
Can specify the name of the output file csc /out:firstprogram.exe firstc.cs

/target:exe /target:library /target:module /target:winexe


Can specify the type of output file

Copyright 2005, 28 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Compile Switches
Error report /bugreport:file
Can generate an error report, all the compilation errors are stored in the file csc /bugreport:error.txt firstc#.cs

Contains
Copy of all course code files in the compilation List of compiler option used in the compilation Version information about the compiler, run time and operating system Output generated by the compiler

Copyright 2005, 29 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Assemblies
Assemblies are fundamental building blocks of a .NET Framework application. They contain the types and resources that make up an application and describe those contained types to the CLR. An assembly consists of four internal parts:
Assembly Manifest or Metadata Type Metadata IL code Resource files

Copyright 2005, 30 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Class Library Assemblies


Class Library assemblies represent sets of types that can be referenced and used in other assemblies.

TestDLL

My ssembly

Test ssembly

Copyright 2005, 31 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Private and Shared Assemblies


Assemblies can be either private or shared. A private assembly is an assembly that is used by one application only. A private assembly is integral to the application. Private assemblies do not have version or identity issues A shared assembly can be used by multiple applications.

Copyright 2005, 32 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Private and Shared Assemblies


A shared assembly can be used by multiple applications. Only one copy of shared assemblies is present per machine. An assembly is shared by installing it to the Global Assembly Cache. Reasons for being in GAC
Shared Location Security Side by Side Versioning

Copyright 2005, 33 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Strong Naming
A strong name is a name that guarantees an assembly identity. Consists of - Name of assembly - Version number - Public key of public/private key pair A strong name can be generated with sn.exe

Copyright 2005, 34 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Steps to create an Shared Assembly


Step 1 : In the .Net IDE, from the File menu, choose New and then choose Project. The New Project window opens. Step 2 : In the New Project window, select Visual C# Projects, and then choose Class Library .Specify name as TestLib and path as C:\SharedAssembly (Please a create the folder SharedAssembly before) Step 3: Write the following code in class library

Copyright 2005, 35 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Steps to create an Shared Assembly


using System; namespace TestLib { /// <summary> /// Summary description for Class1. /// </summary> public class MathsFunction { public MathsFunction() { // // TODO: Add constructor logic here // } public int multiply(int x, int y) { return x*y; } } }

Copyright 2005, 36 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Steps to create an Shared Assembly


Step 4: Compile it. Step 5 : Move to .NET Command prompt and change path to C:\SharedAssembly\ TestLib Step 6: Type at the given prompt sn k testkey.snk Step 7: In IDE,thru Solution Explorer ,open AssemblyInfo.cs and change [assembly: AssemblyVersion("1.0.*")] to [assembly: AssemblyVersion("1.0.0.0")] Step 8: Also,change [assembly: AssemblyKeyFile] to [assembly: AssemblyKeyFile(@"C:\SharedAssembly\TestLib\testkey.snk")]

Copyright 2005, 37 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Steps to create an Shared Assembly


Step 9 : Compile and Build it. Step 10 : Move to .NET Command Prompt and change path to C:\SharedAssembly\TestLib\bin\Debug Step 11 : Give the command at the said prompt as gacutil /i TestLib.dll Step 12: Verify at C:\Windows\assembly , an entry for TestLib exists.

Copyright 2005, 38 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Steps for using an Shared Assembly


Step 1: In the .Net IDE, from the File menu, choose New and then choose Project. The New Project window opens. Step 2: In the New Project window, select Visual C# Projects, and then choose Console Application and name it as TestClient. Step 3: From Project menu, select Add Reference to the above created dll (thru Browse). (dll would be present in the following path C:\SharedAssembly\TestLib\bin\debug\TestLib.dll) Step 4: Write the following code in the Console Application TestClient

Copyright 2005, 39 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Steps for using an Shared Assembly


using System; namespace TestClient { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { TestLib.MathsFunction obj = new TestLib.MathsFunction (); Console.WriteLine (obj.multiply(5,5)); } } }

Copyright 2005, 40 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Steps for using an Shared Assembly


Step 5 : Compile and Run the TestClient Application.

Copyright 2005, 41 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Versioning
Step 1: In AssemblyInfo.cs of TestLib change Assembly Version to 2.0.0.0 Step 2 : In .cs file,change in multiply() return x*y to 2*x*y Step 3 : Rebuild the class library and publish again using gacutil. Step 4: Recompile TestClient application , it now uses Version 2.0. Step 5 : Verify at C:\Windows\assembly , two entries for TestLib exists.

Copyright 2005, 42 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Configuration File
Step 1: Open TestClient.sln. Step 2: From Project Menu, selct Add - > New Item -> Application Configuration File and click on Open. App.config is added. Step 3 : Click on Start->All Programs -> Microsoft .NET SDK FrameWork -> Documentation. Step 4 : Look for bindingredirect Step 5: From the given example copy and paste the entire contents between <configuration></configuration> in App.config.

Copyright 2005, 43 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Configuration File
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="myAssembly" publicKeyToken="32ab4ba45e0a69a1" culture="neutral" /> <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration>

Copyright 2005, 44 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Configuration File
Step 6: Change assembly name to TestLib . Step 7 : Change public key token. For it thru Windows Explorer, move to location c:\Windows\assembly and select TestLib. Step 8: Right Click on TestLib and select Properties.Copy and Paste public key token in App.config file. Step 9 : Rebuild application. Run TestClient.exe from the .NET command prompt and path C:\SharedAssembly\TestClient\bin\debug. Version 2.0 will be used. Step 10: In order to use,Version 1.0,open App.config and interchange old and new version. Step 11 : Rebuild application. Run TestClient.exe from the .NET command prompt and path C:\SharedAssembly\TestClient\bin\debug. Version 1.0 will be used.

Copyright 2005, 45 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Summary
Interface Properties Indexers Collections Introduction to Preprocessor directive Compiler Switches Assemblies
Private Public Versioning

Copyright 2005, 46 Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

Thank You!
Copyright 2005, 47 Infosys Technologies Ltd ER/CORP/CRS/LA30FC/003 Version no: 2.0

You might also like