DCIT 318 Programming II - Session 1 PDF
Document Details
University of Ghana
2024
Mr. Paul Ammah
Tags
Summary
This document is a presentation on C# and .NET framework. It covers the introduction to .NET, generations of .NET framework, and its benefits. The document also describes the core components of .NET framework and its architecture.
Full Transcript
DCIT 318 PROGRAMMING II Session 1 – Introduction to C# and.NET framework Lecturer: Mr. Paul Ammah, CSD Contact Information: [email protected] Department of Computer Science School of Physical and Mathematical Sciences 2023/2024 Introduction to.NET The.NET Framework is one of...
DCIT 318 PROGRAMMING II Session 1 – Introduction to C# and.NET framework Lecturer: Mr. Paul Ammah, CSD Contact Information: [email protected] Department of Computer Science School of Physical and Mathematical Sciences 2023/2024 Introduction to.NET The.NET Framework is one of the most popular widely used integrated software development environments today..NET Framework allows the integration of codes written in different programming languages. Earlier each language required different execution environments. But with the introduction of.NET framework this problem was solved..NET Framework provides programmers a single platform to develop Windows and Web applications in various programming languages, such as Visual Basic(VB) andSlide Visual 2 C# Generations of.NET Framework.NET Framework 1.0.NET Framework 1.1.NET Framework 2.0.NET Framework 3.0.NET Framework 3.5.NET Framework 4.0(release year-2010).NET Framework 4.5(release year-2012).NET Framework 4.6(release year-2015).NET Framework 4.7(release year-2017) …..NET Framework 6.0.NET Framework 7.0 Slide 3 Benefits of.NET Framework Consistent Programming Model: By using this model different tasks such as Database Connectivity, Reading from and Writing to files is performed. Language Interoperability: Piece of code written in one language can be used in another language. Automatic Management of Resources: Garbage Collection(Part of CLR) performs the allocation and de allocation of all the resources such as files, memory and database connections. Programmer does not need to provide code for memory management tasks. Ease of Deployment: Applications coded under.NET Framework can be easily deployed(installed on computer) because deployment is done in the form of assemblies which are the single , logical deployment unit and hence registries does not need to store information about components and applications. Slide 4 Core Components of.NET Framework Common Language Runtime Common Type System Common Language Specification.NET Framework Class Library(Base Class Library) Windows Forms ASP.NET and ASP.NET Ajax ADO.NET WPF and WCF Slide 5.NET Architecture Slide 6.NET Framework ASP.NET ASP.NET Windows WindowsForms Forms Web Services Web Forms Controls Drawing ASP.NET Application Services Windows Application Services Framework FrameworkClass ClassLibrary Library ADO.NET XML Threading IO Network Security Diagnostics Etc. Common CommonLanguage LanguageRuntime Runtime Memory Management Common Type System Lifecycle Monitoring Slide 7 Common Language Runtime A Common Language Runtime (CLR) provides essential runtime services such as automatic memory management and exception handling. The CLR is at the core of the.NET platform - the execution engine. A unifying framework for designing, developing, deploying, and executing distributed components and applications. Loads and runs code written in any runtime-aware programming language Manages memory, thread execution, type safety verification and garbage collection. Performs compilation (Just In-time Compiler) Makes use of a new common type system capable of expressing the semantics of most modern programming languages. The common type system defines a standard set of types and rules for creating new types. Slide 8 MSIL and JIT Compilation Source code is compiled into MSIL (Microsoft Intermediate Language). Similar to Java bytecode. MSIL allows for runtime type-safety and security, as well as portable execution platforms (all Windows). MSIL code cannot play tricks with pointers or illegal type conversions. The MSIL architecture results in apps that run in one address space - thus much less OS overhead. Compilers also produce “metadata”: – Definitions of each type in your code. – Signatures of each type’s members. – Members that your code references. – Other runtime data for the CLR. Metadata along with the MSIL enables code to be self-describing - no need for separate type libraries, IDL, or registry entries. When code is executed by the CLR, a JIT compilation step occurs. Code is compiled method-by-method to native machine code. Slide 9 Packaging: Modules, Types, Assemblies, and the Manifest Assembly Assembly Manifest Module Metadata MSIL Type Type Type Slide 10 Packaging: Modules, Types, Assemblies, and the Manifest A module refers to a binary, such as an EXE or DLL. Modules contain definitions of types, such as classes, interfaces, structures, and enumerations. An assembly contains a manifest, which is a catalog of component metadata containing: – Assembly name. – Version (major, minor, revision, build). – Assembly file list - all files contained in the assembly. – Type references - mapping the managed types included in the assembly with the files that contain them. – Scope - private or shared. – Referenced assemblies. No MSIL code can be executed unless there is a manifest associated with it. Slide 11.NET Tools Microsoft Visual Studio.NET and Microsoft.NET Framework supplies complete solution for developers to build, deploy and run XML services Visual Studio.NET is the next generation of Microsoft’s popular multi- language development tool built especially for.NET Enhances existing languages like Visual Basic with new OO features Introduces C# Slide 12 Microsoft C# A modern, object-oriented programming language built from the ground up to exploit the power of XML-based Web services on the.NET platform. The main design goal of C# was simplicity rather than pure power. Features of C# Simplicity Type Safety Consistency Version Control Modernity Compatibility Object Orientation Flexibility Slide 13 C# Language C# is type-safe object-oriented language Enables developers to build a variety of secure and robust applications Very similar in syntax to C, C++, and Java. Syntax is highly expressive. Key features: nullable value type, enumerations, delegates, lambda expressions, and direct memory access Slide 14 Compile-time and Run-time Relationships of C# Slide 15 C# Program Structure Namespaces – Contain types and other namespaces Type declarations – Classes, structs, interfaces, enums, and delegates Members – Constants, fields, methods, properties, indexers, events, operators, constructors, destructors Organization – No header files, code written “in-line” – No declaration order dependence Slide 16 Type System Value types – Directly contain data – Cannot be null Reference types – Contain references to objects – May be null int i = 123; string s = "Hello world"; Slide 17 Type System Value types – Primitives int i; – Enums enum State { Off, On } – Structs struct Point { int x, y; } Reference types – Classes class Foo: Bar, IFoo {...} – Interfaces interface IFoo: IBar {...} – Arrays string[] a = new string; – Delegates delegateSlide void 18 Empty(); Predefined Types C# predefined types – Reference object, string – Signed sbyte, short, int, long – Unsigned byte, ushort, uint, ulong – Character char – Floating-point float, double, decimal – Logical bool Predefined types are simply aliases for system-provided types – For example, int == System.Int32 Slide 19 Classes Single inheritance Multiple interface implementation Class members – Constants, fields, methods, properties, indexers, events, operators, constructors, destructors – Static and instance members – Nested types Member access – public, protected, internal, private Slide 20 Structs Like classes, except – Stored in-line, not heap allocated – Assignment copies data, not reference – No inheritance Ideal for light weight objects – Complex, point, rectangle, color – int, float, double, etc., are all structs Benefits – No heap allocation, less GC pressure – More efficient use of memory Slide 21 Decision Statements If..else if..else Ternary Operators (?:) Switch Statements Slide 22 The if statement void DisplayCharacter(char ch) { if (char.IsUpper(ch)) { Console.WriteLine($"An uppercase letter: {ch}"); } else if (char.IsLower(ch)) { Console.WriteLine($"A lowercase letter: {ch}"); } else if (char.IsDigit(ch)) { Console.WriteLine($"A digit: {ch}"); } else { Console.WriteLine($"Not alphanumeric character: {ch}"); } } Slide 23 Switch Statements void DisplayMeasurement(double measurement) { switch (measurement) { case < 0.0: Console.WriteLine($"Measured value is {measurement}; too low."); break; case > 15.0: Console.WriteLine($"Measured value is {measurement}; too high."); break; case double.NaN: Console.WriteLine("Failed measurement."); break; default: Console.WriteLine($"Measured value is {measurement}."); break; } } Slide 24 Tenary Operator The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false string weatherDisplayString = tempInCelsius < 20.0 ? "Cold." : "Perfect!"; Slide 25 Iteration statements while loop For loop Foreach loop Do loop Slide 26 The for statement The for statement executes a statement or a block of statements while a specified Boolean expression evaluates to true for (int i = 0; i < 3; i++) { Console.Write(i); } Slide 27 The foreach statement The foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface var fibNumbers = new List { 0, 1, 1, 2, 3, 5}; foreach (int element in fibNumbers) { Console.Write($"{element} "); } Slide 28 The while statement The while statement executes a statement or a block of statements while a specified Boolean expression evaluates to true int n = 0; while (n < 5) { Console.Write(n); n++; } Slide 29 The do statement The do statement executes a statement or a block of statements while a specified Boolean expression evaluates to true. Because that expression is evaluated after each execution of the loop, a do loop executes one or more times. int n = 0; do { Console.Write(n); n++; } while (n < 5); Slide 30 C# Special Characters Special characters are predefined, contextual characters that modify the program element (a literal string, an identifier, or an attribute name) to which they are prepended. C# supports the following special characters: – @, the verbatim identifier character. – $, the interpolated string character. Slide 31 Verbatim text - @ in variables, attributes, and string literals The @ special character serves as a verbatim identifier. You use it in the following ways: – To indicate that a string literal is to be interpreted verbatim – To use C# keywords as identifiers – To enable the compiler to distinguish between attributes in cases of a naming conflict Slide 32 Verbatim String Literal string filename1 = @"c:\documents\files\u0066.txt"; string filename2 = "c:\\documents\\files\\u0066.txt"; Console.WriteLine(filename1); Console.WriteLine(filename2); // The example displays the following output: -> c:\documents\files\u0066.txt -> c:\documents\files\u0066.txt Slide 33 C# keywords as identifiers The @ character prefixes a code element that the compiler is to interpret as an identifier rather than a C# keyword string[] @for = { "John", "James", "Joan", "Jamie" }; for (int ctr = 0; ctr < @for.Length; ctr++) { Console.WriteLine($"Here is your gift, {@for[ctr]}!"); } // The example displays the following output: // Here is your gift, John! // Here is your gift, James! // Here is your gift, Joan! // Here is your gift, Jamie! Slide 34 String interpolation using $ The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. String interpolation provides a more readable, convenient syntax to format strings. Slide 35 String interpolation using $ string name = "Mark"; var date = DateTime.Now; // Composite formatting: Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date); // String interpolation: Console.WriteLine( $"Hello, {name}! Today is {date.DayOfWeek}, it’s {date:HH:mm} now.” ); Slide 36 Raw string literal text - """ A raw string literal starts and ends with a minimum of three double quote (") characters Raw string literals can span multiple lines var xml = """ """; Slide 37