Introduction to C# PDF

Summary

This document provides an introduction to the C# programming language, covering its origins, development milestones, and key features. It details core concepts like Generics, which allow type-safe collections and methods. The document also mentions other language features such as Anonymous Methods and Iterators.

Full Transcript

INTRODUCTION TO C# Anonymous Methods: helped developers write more 1. ORIGIN AND DEVELOPMENT: C# flexible and concise code. C# Creation and Microsoft’s Role (2000)...

INTRODUCTION TO C# Anonymous Methods: helped developers write more 1. ORIGIN AND DEVELOPMENT: C# flexible and concise code. C# Creation and Microsoft’s Role (2000) As the name suggests, an anonymous method is a C# was developed by Microsoft as part of its.NET initiative, method without a name. Anonymous methods in C# can be led by Anders Hejlsberg. The goal was to create a modern, defined using the delegate keyword and can be assigned to object-oriented programming language that would be simple, a variable of delegate type. efficient, and secure, designed for the.NET Framework. Func sum = delegate (int a, int b) { return a + It was introduced to address some limitations in languages like b; }; C++ and Java, providing a powerful yet user-friendly tool for Console.WriteLine(sum(3, 4)); // output: 7 developers. Iterators: Simplified the process of enumerating through Initial Release - C# 1.0 (2002) collections. Released with Visual Studio.NET, C# 1.0 focused on Iterators are methods that iterate collections like lists, ○ core object-oriented principles tuples, etc. Using an iterator method, we can loop through ○ garbage collection - automatically free up memory space an object and return it's elements. that has been allocated to objects no longer needed by the To create an iterator method, we use yield return program. keyword to return the value. ○ exception handling - an unexpected event that occurs The return type of the iterator method is during program execution. For example: either IEnumerable, IEnumerable, IEnumerator, “int divideByZero = 7 / 0;” or IEnumerator. The above code causes an exception as it is not possible to divide a number by 0. Exceptions abnormally terminate the flow of the program instructions, we need to handle those exceptions. try-catch, try-finally, and try-catch-finally statements. The try block then throws the exception to the catch block which handles the raised exception. The finally block is always executed whether there is an exception or not. ○ and familiar C/C++ style syntax. The language was tightly integrated with the Common Language Runtime (CLR) for cross-language compatibility. 2. KEY EVOLUTION MILESTONES: C# Output: C# 2.0 (2005) - Introduced significant language enhancements: Sunday Generics: Allowed for creating type-safe collections and 2 methods. Here, getString() is an iterator method that A generics class is used to create an instance of any data returns "Sunday" and 2 using yield return. type. To define a generics class, we use angle brackets () as: C# 3.0 (2007) Here, we have created a generics class named Student. T Key innovations: used inside the angle bracket is called the type parameter. LINQ (Language Integrated Query): Allowed querying data While creating an instance of the class, we specify the data (from collections, databases, XML, etc.) using C# syntax. type of the object which replaces the type parameter. In the above example, we have created a generics class Lambda Expressions: Enabled more concise and functional named Student. Also, we have defined a constructor that programming patterns. prints this value. Lambda Expression is a short block of code that Inside the Main class, we have created two instances of accepts parameters and returns a value. It is defined as an the Student classes: studentName and studentId. The type anonymous function (function without a name). For parameter T of Student is replaced by: example: string - in studentName num => num * 7 int - in studentId Here, num is an input parameter and num * 7 is a return Here, the Student class works with both the int and value. The lambda expression does not execute on its own. the string data type. Instead, we use it inside other methods or variables. We can define lambda expression in C# as, Named and Optional Parameters: Simplified function calls “(parameterList) => lambda body” with default values. parameterList - list of input parameters Named arguments enable you to specify an argument for => - a lambda operator a parameter by matching the argument with its name rather lambda body - can be an expression or statement than with its position in the parameter list. For example, a function that prints order details (such as, seller name, order number & product name) can be called by sending arguments by position, in the order defined by the function. “PrintOrderDetails("Gift Shop", 31, "Red Mug");” If you don't remember the order of the parameters but know their names, you can send the arguments in any order. “PrintOrderDetails(orderNum: 31, productName: "Red Mug", sellerName: "Gift Shop");” “PrintOrderDetails(productName: "Red Mug", sellerName: "Gift Shop", orderNum: 31);” Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. For example, in the following code, instance method ExampleMethod is defined with one required and two optional parameters. “public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)” The following call to ExampleMethod causes a compiler error, because an argument is provided for the third parameter but not for the second. “//anExample.ExampleMethod(3, ,4);” However, if you know the name of the third parameter, you can use a named argument to accomplish the task. “anExample.ExampleMethod(3, optionalint: 4);” C# 5.0 (2012) Major improvements: Asynchronous Programming (async/await): Revolutionized how developers wrote asynchronous and concurrent code, Extensions Methods: Allowed adding methods to existing making it more readable and maintainable. types without modifying them. C# 4.0 (2010) Focused on improving interoperability with dynamic programming languages: Dynamic Type: Enabled dynamic typing for easier interaction with COM objects, and dynamic languages like Python, or JavaScript. C# 6.0 (2015) C# 7.0 and 7.1 (2017) Focused on improving syntax: Enhancements to make the language more expressive: Auto-Property Initializers: Simplified property declarations. Tuples: Introduced lightweight data structures for returning multiple values Null-Conditional Operators (?.): Reduced the risk of NullReferenceException by providing concise syntax for null checks. String Interpolation ($): Simplified string formatting by embedding expressions within string literals. Pattern Matching: Allowed more expressive and functional Asynchronous Streams (Async Iterators): Enhanced async code by matching patterns in switch statements and other programming, making it easier to work with data streams. contexts. Switch Expressions: Further modernized pattern-matching ○ Pattern matching in C# allows you to test whether a syntax. value fits a certain pattern and extract data from that value. ○ It simplifies conditional logic by enabling type checks, value checks, and decomposing data structures in a more concise and readable manner. C# 9.0 (2020) Focused on immutability and simplifying code: Records: Introduced for creating immutable, lightweight data objects. Immutable means it cannot change. By default, Record types are immutable. Record Type is a compact and easy way to write reference types (immutable) that automatically behave like value types. Local Functions: Enabled defining functions inside other functions for encapsulation. Init-Only Properties: Allowed setting properties only during initialization, improving immutability C# 10.0 (2021) Aimed at reducing boilerplate code: Global Usings: Simplified managing namespaced by defining common using directives globally across files. C# 8.0 (2019) Introduced: Nullable Reference Types: Improved null safety by distinguishing between nullable and non-nullable reference types. The compiler tracks the null-state of every expression in your code at compile time. The null-state has one of three values: not-null: The expression is known to be not-null. maybe-null: The expression might be null. oblivious: The compiler can't determine the null-state of the expression. File-Scoped Namespaces: Allowed for more compact Required Members: Ensured that certain members were namespace declarations. initialized during object creation, further improving File scoped namespaces use a less verbose format for the immutability practices. typical case of files containing only one namespace. This action removes the curly braces from the namespace declarations and terminates the top-level declaration with a ;. Code goes from this: Record Structs: Extended records to support value types, 3. IMPACT OF.NET CORE AND.NET 5+ C# offering benefits or records for structs. NET Core Introduction (2016) C# 11.0 (2022) Microsoft introduced.NET Core to allow C# and.NET to be Recent improvements include: cross-platform (Windows, macOS, Linux) Raw String Literals: made working with multi-line and This was a shift to the Windows-only.NET Framework. special-character strings easier without requiring extensive.NET 5 (2020) and Beyond escaping. With the release of.NET 5, Micorosft unified.NET Core and A raw string literal starts and ends with a minimum of three.NET framework under a single platform. double quote (") characters: This allowed C# to be used seamlessly across different var singleLine = """This is a "raw string literal". It can platforms and environments, including web development, contain characters like \, ' and "."""; desktop applications, mobile development, cloud services, and even game development through Unity. Raw string literals can span multiple lines: 4. MODERN USE AND FUTURE OF C# C# continues to be a versatile and evolving language, widely var xml = """ used in enterprise applications, web development (with ASP.NET), mobile apps (via Xamarin), and game development (with Unity). Microsoft’s ongoing updates ensure that C# remains modern, flexible, and competitive with newer languages. """; As of now, C# is evolving towards supporting even more Generic Math: Provided a more robust system for working functional programming features, enhancing performance, with numeric types across generics. and simplifying the development of cloud-native applications. II. SETTING UP THE DEVELOPMENT ENVIRONMENT C# https://www.youtube.com/watch?v=HUbWg_11MUY&t=48s &ab_channel=NoAIRex BASIC STRUCTURE OF A C# PROGRAM A Minimal C# Program must include: A namespace (to organize code and avoid name conflicts) A class (the building block of C# programs) A Main method (entry point of the application) Explanation of the Example: 1. using System; - This directive imports the System namespace, which provides essentials like Console. It allows us to use its functionalities without fully qualifying the names. 2. namespace HelloWorldApp - The namespace is used to group classes and organize code. In larger programs, namespaces help avoid naming conflicts. 3. class Program - the class keyword defines a new class. In C#, everything is encapsulated in classes. Program is the name of the class that contains the Main method. 4. static void Main(String[] args) - The Main method is the entry point for every C# console application. When the program runs, execution starts here: static: The method is called on the class itself, not on an instance of the class. void: the method does not return a value For loop: string [] args: represents command-line arguments passed on the program 5. Console.WriteLine(“Hello, World!”); - this line prints the string “Hello, World!” to the console. Console is a class in the System namespace that provides methods for input and output. COMMENTS / VARIABLES AND DATA TYPES / OPERATORS While loop: FUNCTIONS AND METHODS Arithmetic Operators: Methods are blocks of code that perform specific tasks. The Main method is an example of this. Comparison Operators: Logical Operators: Explanation: Conditional Statements: Add Method: it takes two integers a and b as input parameters, adds them, and returns the sum. Calling a Method: The Add method is called in Main, and the result is printed. SUMMARY OF C# SYNTAX FEATURES Case-sensitive: C# differentiates between main and Main. Statements end with a semicolon: each line of executable code is typically followed by a ; Code is organized in classes: Even the simplest C# program needs at least one class Switch Statement: COMMON ERRORS IN C# SYNTAX Missing Semicolon: Forgetting to terminate a statement with a semicolon will result in a compile-time error. Case Sensitivity: Misnaming method or variable identifiers (e.g., using main instead of Main). Mismatched Braces: Every { must have a corresponding }

Use Quizgecko on...
Browser
Browser