C Advanced Concept ISRAR ALI Hammad Khan Namespaces

  • Slides: 38
Download presentation
C# Advanced Concept [ISRAR ALI] Hammad Khan

C# Advanced Concept [ISRAR ALI] Hammad Khan

Namespaces and Assemblies • The namespace keyword is used to declare a scope. •

Namespaces and Assemblies • The namespace keyword is used to declare a scope. • Making software components reusable can result in naming collisions (two classes defined by two programmers can have the same name). using System. Collections; • An assembly is a dynamic link library created when compiling a project. The assembly can be found in the binDebug folder of the project. • By default, the assembly name will include the namespace name

Example // Namespace Declaration using System; // The C# Station Tutorial Namespace namespace csharp_station

Example // Namespace Declaration using System; // The C# Station Tutorial Namespace namespace csharp_station { namespace tutorial { // Program start class Namespace. CSS { // Main begins program execution. public static void Main() { // Write to console Console. Write. Line("This is the new C# Station Tutorial Namespace. "); } }

Methods and Parameter Modifiers • Methods Are Actions • methods can be implemented within

Methods and Parameter Modifiers • Methods Are Actions • methods can be implemented within the scope of classes or structures • prototyped within interface types • may be decorated with various keywords (internal, virtual, public, new, etc. ) // static return. Val Method. Name(args) {. . . } class Program { static int Add(int x, int y) { return x + y; } }

Parameter-Passing Behavior static void Main(string[] args) { Console. Write. Line("***** Fun with Methods *****");

Parameter-Passing Behavior static void Main(string[] args) { Console. Write. Line("***** Fun with Methods *****"); // Pass two variables in by value. int x = 9, y = 10; Console. Write. Line("Before call: X: {0}, Y: {1}", x, y); Console. Write. Line("Answer is: {0}", Add(x, y)); Console. Write. Line("After call: X: {0}, Y: {1}", x, y); Console. Read. Line(); } static int Add(int x, int y) { int ans = x + y; // Caller will not see these changes as you are modifying a copy of the original data. x = 10000; y = 88888; return ans; }

Keyword ref void My. Method() { int num 1 = 7, num 2 =

Keyword ref void My. Method() { int num 1 = 7, num 2 = 9; Swap(ref num 1, ref num 2); // num 1 = 9, num 2 = 7 } void Swap(ref int x, ref int y) { int temp = x; x = y; y = temp; }

Keyword out void My. Method() { int num 1 = 7, num 2; Subtraction(num

Keyword out void My. Method() { int num 1 = 7, num 2; Subtraction(num 1, out num 2); // num 1 = 7, num 2 = 5 } void Subtraction(int x, out int y) { y = x - 2; // y must be assigned a value } uninitialised

Keyword params void My. Method() { int sum = Addition(1, 2, 3); // sum

Keyword params void My. Method() { int sum = Addition(1, 2, 3); // sum = 6 } int Addition(params int[] integers) { int result = 0; for (int i = 0; i < integers. Length; i++) result += integers[i]; return result; }

Method Overloading class Program { static void Main(string[] args) { } // Overloaded Add()

Method Overloading class Program { static void Main(string[] args) { } // Overloaded Add() method. static int Add(int x, int y) { return x + y; } static double Add(double x, double y) { return x + y; } static long Add(long x, long y) { return x + y; } }

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING

Object-oriented programming (OOP) is a programming paradigm that uses objects and data structures consisting

Object-oriented programming (OOP) is a programming paradigm that uses objects and data structures consisting of data fields and methods together with their interactions to design applications and computer programs. Programming techniques may include features such as Information Hiding, Data Abstraction, Encapsulation, Modularity, Polymorphism, and Inheritance

Objects • Everything is an object. Think of an object as a fancy variable.

Objects • Everything is an object. Think of an object as a fancy variable. it stores data, but you can “make requests” to that object, asking it to perform operations on itself. • A program is a bunch of objects telling each other what to do by sending messages. • Each object has its own memory made up of other objects. • Every object has a type. • All objects of a particular type can receive the same messages. An object has state, behavior and identity This means that an object can have internal data (which gives it state), methods (to produce behavior), and each object can be uniquely identified.

Abstraction and Classes • The ability to generalize an object as a data type

Abstraction and Classes • The ability to generalize an object as a data type that has a specific set of characteristics and is able to perform a set of actions. • Object-oriented languages provide abstraction via classes. Classes define the properties and methods of an object type. ▫ You can create an abstraction of a dog with characteristics, such as color, height, and weight, and actions such as run and bite. The characteristics are called properties, and the actions are called methods. ▫ Classes are blueprints for Object and Objects are instance of classes.

Class Example public class My. Array { private const int MAX_LENGTH = 100; private

Class Example public class My. Array { private const int MAX_LENGTH = 100; private int length; public My. Array() { length = 0; } public int Length { get { return length; } set { length = value; } } }

Class Definitions • • • None or Internal Public Abstract or internal abstract Public

Class Definitions • • • None or Internal Public Abstract or internal abstract Public abstract Sealed or internal sealed Public sealed

Class Constructors • A constructor is called automatically right after the creation of an

Class Constructors • A constructor is called automatically right after the creation of an object to initialize it. • Constructors have the same name as their class names • Default constructor: if no constructor is declared, a parameterless constructor can be declared • A class can contain default constructor and overloaded constructors to provide multiple ways to initialise objects. • Static constructor: similar to static method. It must be parameterless and must not have an access modifier (private, public).

Class Constructor Example public class Languages { static Languages() // static constructor {. .

Class Constructor Example public class Languages { static Languages() // static constructor {. . . } public Languages() // default constructor {. . . } public Languages(string lang) // overloaded constructor {. . . } } public class My. Class() { Languages langs = new Languages(); }

Class Method Example public class CSharp { public CSharp () {. . . }

Class Method Example public class CSharp { public CSharp () {. . . } public static void Static. Method() {. . . } public void Non. Static. Method() {. . . } } public class My. Class() { CSharp cs = new CSharp(); cs. Non. Static. Method(); CSharp. Static. Method(); }

Class Property public class CSharp { private int count = 0; . . .

Class Property public class CSharp { private int count = 0; . . . public int Count { get { return count; } internal set { count = value; } } public class My. Class() { CSharp cs = new CSharp(); cs. Count = 5; int num = cs. Count; }

Class Indexer public class CSharp { int [] vals = new int [10]; .

Class Indexer public class CSharp { int [] vals = new int [10]; . . . public int this [int i] { get { return vals[i]; } } } public class My. Class() { CSharp cs = new CSharp(); int num = cs[2]; }

Nested Class • Nested types can see all the members of their closing type,

Nested Class • Nested types can see all the members of their closing type, both private and public ones. • External types only see nested types if they are declared as public. • Fields of inner types and outer types belong to different objects. We must specify the object to which they belong when we want to access them. In Java, inner classes can access fields of outer class public class My. Class { private class Nested. Class { } }

Class Inheritance • Inheritance is a form of software reusability in which classes are

Class Inheritance • Inheritance is a form of software reusability in which classes are created by reusing data and behaviours of an existing class with new capabilities. • Inheritance combines with object composition to create the primary techniques for reusing software • A class inheritance hierarchy begins with a base class that defines a set of common attributes and operations that it shares with derived classes. • A derived class inherits the resources of the base class and overrides or enhances their functionality with new capabilities. • The classes are separate, but related

Class Accessibility • public: access is not restricted • private: access is limited to

Class Accessibility • public: access is not restricted • private: access is limited to the containing type • protected: access is limited to the containing class or types derived from the containing class • internal: access is limited to the current assembly • protected internal: access is limited to the current assembly or types derived from the containing class

Abstract Class, Abstract Methods and Virtual Methods • Abstract class is normally used as

Abstract Class, Abstract Methods and Virtual Methods • Abstract class is normally used as a base class and never intended to instantiate any objects. • The use of polymorphism requires declaring virtual or abstract methods and properties in the abstract base class and overriding them in the derived classes. • Any class with an abstract method in it must be declared abstract. • Abstract methods do not have an implementation in the abstract base class and every concrete derived class must override all base-class abstract methods and properties using keyword override. • Virtual methods have an implementation in the abstract base class and its derived classes have an option of overriding the method

Examples Abstract class: public abstract class Abstract. Class { public Abstract. Class() { }

Examples Abstract class: public abstract class Abstract. Class { public Abstract. Class() { } public abstract int Abstract. Method(); public virtual int Virtual. Method() { return 0; } }

Examples Derived class: public class Derived. Class : Abstract. Class { public Derived. Class()

Examples Derived class: public class Derived. Class : Abstract. Class { public Derived. Class() {} public override int Abstract. Method() { return 0; } public override int Virtual. Method() { return base. Virtual. Method (); } }

Sealed Class • The keyword sealed is applied to classes and methods to prevent

Sealed Class • The keyword sealed is applied to classes and methods to prevent overriding and inheritance. • A method declared sealed cannot be overridden in a derived class • Static methods and private methods are implicitly sealed. • Recall that a method can be overridden if it is declared either virtual or abstract. The keyword sealed is not applied to these cases. However, we can use the keyword sealed for methods we have overridden and we do not want to override it in further derived classes. • A sealed class cannot be a base class since it cannot be inherited and hence it cannot have any derived classes. • All methods in a sealed class are sealed implicitly

Sealed Class Example sealed class Sealed. Class { public int x; public int y;

Sealed Class Example sealed class Sealed. Class { public int x; public int y; } class My. Class { Sealed. Class sc = new Sealed. Class(); sc. x = 10; sc. y = 20; } class In. Class : Sealed. Class // error: cannot inherit { }

Partial Class • All source code for a type is normally in a single

Partial Class • All source code for a type is normally in a single file • Sometimes a type becomes large enough that this is an impractical constraint. • Partial types allow classes and interfaces to be broken into multiple pieces stored in different source files for easier development and maintenance. • Additionally, partial types allow separation of machine-generated and user-written parts of types so that it is easier to augment code generated by a tool

Partial Class Example public class Student { private int student. ID; private int name;

Partial Class Example public class Student { private int student. ID; private int name; } public Student () {. . . } public Change. Name() {. . . } public Change. ID () { … } public partial class Student { private int student. ID; public Student () {. . . } } public partial class Student { private int name; public Change. Name() {. . . } public Change. ID () {. . . } }

Interface • An interface definition begins with a keyword interface and contains a set

Interface • An interface definition begins with a keyword interface and contains a set of public methods and properties that have no default implementation to inherit. • An interface must be declared as public interface IStudent { int Student. ID {get; set; } void Add. Subject(string subject. Name); } • Interfaces can be implemented by classes. • An interface defines a contract. This means that a class that implements an interface must provide implementations for every method and property specified in the interface definition.

Class implementing Interface public class Student : IStudent { private int student. ID =

Class implementing Interface public class Student : IStudent { private int student. ID = 0; private Array. List subjects = null; public Student() {} public int Student. ID { get { return student. ID; } set { student. ID = value; } } public void Add. Subject(string subject. Name) { subjects. Add(subject. Name); } }

Generics public class List<T> {{ private object[] T[] elements; private int count; public void

Generics public class List<T> {{ private object[] T[] elements; private int count; public void Add(object Add(T element) { { ifif (count == == elements. Length) Resize(count ** 2); elements[count++] == element; }} }} public object T this[int index] { { List<int> = List(); new List<int>(); List int. List =}} new get {{ return elements[index]; set {{ elements[index] == value; }} int. List. Add(1); // No boxing is boxed Argument }} int. List. Add(2); // No boxing is boxed Argument // Compile-time Should be an error public int Count {{ int. List. Add("Three"); get {{ return count; }} int i = int. List[0]; (int)int. List[0]; // No cast//required Cast required }}

Generics • Why generics? ▫ Type checking, no boxing, no downcasts ▫ Increased sharing

Generics • Why generics? ▫ Type checking, no boxing, no downcasts ▫ Increased sharing (typed collections) • How are C# generics implemented? ▫ ▫ Instantiated at run-time, not compile-time Checked at declaration, not instantiation Work for both reference and value types Exact run-time type information

List<T> Dictionary<K, V> Sorted. Dictionary<K, V> Stack<T> Queue<T> Generics • Collection classes • Collection

List<T> Dictionary<K, V> Sorted. Dictionary<K, V> Stack<T> Queue<T> Generics • Collection classes • Collection interfaces • Collection base classes • Utility classes • Reflection IList<T> IDictionary<K, V> ICollection<T> IEnumerable<T> IEnumerator<T> IComparable<T> IComparer<T> Collection<T> Keyed. Collection<T> Read. Only. Collection<T> Nullable<T> Event. Handler<T> Comparer<T>

Generic Class public class Non. Generic { object item; public object Item { get

Generic Class public class Non. Generic { object item; public object Item { get { return item; } set { item = value; } } } public class Generic<T> { T item; public T Item { get { return item; } set { item = value; } } } public class My. Class() { Non. Generic ng = new Non. Generic (); Generic<int> g = new Generic<int>(); }

Generic Methods static void Add. Multiple<T>(List<T> list, params T[] values) { foreach (T value

Generic Methods static void Add. Multiple<T>(List<T> list, params T[] values) { foreach (T value in values) list. Add(value); } void My. Method() { List<int> list = new List<int>(); Add. Multiple<int>(list, 2, 4, 6); }

Iterators • Methods that incrementally compute and return a sequence of values class Program

Iterators • Methods that incrementally compute and return a sequence of values class Program { static IEnumerable<int> Range(int start, int count) { for (int i = 0; i < count; i++) yield return start + i; } } 0 1 4 9 static IEnumerable<int> Squares(IEnumerable<int> source) { 16 foreach (int x in source) yield return x * x; 25 } 36 49 static void Main() { foreach (int i in Squares(Range(0, 10))) Console. Write. Line(i); 64 81 }