C#-Unit-I 2024-25 Revised.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO UNIT-I Introduction to C# *Introduction- The.NET Framework is a software development platform that was introduced by Microsoft on 13th February 2002.NET stands for Network Enabled Technology. * De...

B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO UNIT-I Introduction to C# *Introduction- The.NET Framework is a software development platform that was introduced by Microsoft on 13th February 2002.NET stands for Network Enabled Technology. * Definition- Framework-Framework in a programming is a tool that provides readymade components used to speed up S/W development. -.NET Framework is a virtual machine for compiling and executing programs written in different languages like C#, VB.Net, J#, F#,C++ etc. -It is also used to create a form based, console-based, mobile and web-based application or services that are available in Microsoft environment. -Furthermore, the.NET framework is a pure object oriented, that is it support all OOP’s Concepts. -.NET framework supports more than 60 programming languages. *.NET Framework Architecture- The first three components from bottom are considered as the basic architecture of.NET framework and after this more components were added by Microsoft in the.NET Framework, Fig-.NET Framework Architecture- Components of.NET Framework 1) CLR (Common Language Runtime)- - CLR is heart and soul of.NET framework. - Used to Execute programs which are written in different languages like C#, VB.Net, J#, F#,C++ etc. *CLR provides a number of services that includes: 1. Loading and executing of programs 2. Memory isolation for application 3. Memory management using automatic garbage collection 4. Providing metadata(basic information about data) SANGOLA COLLEGE SANGOLA 1|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO 5. Verification of type safety 6. Security 7. Interoperability with other system 8. Compilation of IL into native executable code 9. Managing exception and errors CTS (Common Type System) CTS is built in CLR which provides Multiple Language Support. It specifies a standard that represent what type of data and value can be defined and managed in computer memory at runtime. A CTS ensures that programming data defined in various languages should be interact with each other to share information. For example, in C# we define data type as int, while in VB.NET we define integer as a data type hence it does not require any type conversion. 2) BCL (Base Class Library) The base class library has a rich collection of libraries features and functions that help to implement many programming languages in the.NET Framework, such as C #, F #, Visual C ++, and more. Furthermore, BCL divides into two parts: 1. User defined class library  Assemblies –it is a File which is automatically generated by compiler upon successful compilation.  It is the collection of small parts of deployment an application's part.  It contains either the.DLL (Dynamic Link Library) or.exe (Executable) file. 2. Predefined class library  Namespace - It is the collection of predefined classes and methods that present in.NET.  In other languages such as, C we used header files, in java we used package similarly we used "using system" in.NET, where using is a keyword and system is a namespace. FCL (Framework Class Library)-  The Framework Class Library or FCL is a superset of BCL which provides the system functionality in the.NET Framework as it has various classes, data types, interfaces, etc. to perform multiple functions and build different types of applications such as desktop applications, web applications, mobile applications, etc. 3) CLS (Common Language Specification)- CLS is a subset of CTS. It defines a set of rules and restrictions that every language must follow which runs under the.NET framework. The languages which follow these set of rules are said to be CLS Compliant. In simple words, CLS enables cross-language integration or Interoperability. Ex. if we talk about C# and VB.NET then, in C# every statement must have to end with a semicolon. It is also called a statement Terminator, but in VB.NET each statement should not end with a semicolon (;). SANGOLA COLLEGE SANGOLA 2|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO 4)MSIL/CIL(MicrosoftIntermediateLanguage/Common Intermediate Language) – The Microsoft Intermediate Language (MSIL), also known as the Common Intermediate Language (CIL) is a set of instructions that are platform independent and are generated by the language-specific compiler from the source code. The MSIL is platform independent and consequently, it can be executed on any of the Common Language Infrastructure supported environments such as the Windows.NET runtime. The execution process that includes the creation of the MSIL and the conversion of the MSIL into machine code by the JIT compiler is given as follows: 5) Garbage Collector Garbage Collector is responsible for automatic memory management of objects. Also, the responsibility of the garbage collector is removing the object from memory that has no use. Advantages of Garbage Collector  Allows us to develop an application without having worry to free memory.  Allocate main memory for object efficiently on the managed Heap.  Provide security to main memory space by making sure that an object cannot use the content of another object. SANGOLA COLLEGE SANGOLA 3|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO *.NET Core .NET Core, developed by Microsoft, is managed under the.NET Foundation, a non- profit open source organization. .NET Core is written in C# and C++ and licensed under MIT (Massachusetts Institute of Technology) license. The first version,.NET Core 1.0, was released in 2016 with limited functionality. .NET Core is a free, open-source, modular, cross-platform framework for building modern and high-performance applications.  It is a reimplementation of the.NET Framework to be more lightweight, modular, and flexible. .NET Core includes a runtime, a set of libraries, and a development environment that supports multiple programming languages such as C#, Visual Basic, and F#.  It is designed to run on various platforms, including Windows, macOS, and Linux.  It can be used to build a wide range of applications, including web applications, desktop applications, Mobile applications, Cloud applications, Gaming applications, Internet of Things and micro services etc. *Characteristics of.NET Core Key characteristics of.NET Core include open source, cross-platform, modern, flexible, lightweight, fast, friendly, shareable, and built for future software development. 1) Free and Open Source.  The.NET Core platform is free and open source. .NET Core source code project is available on GitHub.  Any developer can get involved in.NET Core development. Thousands of active developers participating in.NET Core development are improving features, adding new features, and fixing bugs and issues. .NET Core is free and licensed under MIT and Apache licenses. 2) Cross-Platform. .NET Core supports and runs on Windows, macOS, and Linux operating systems. .NET Core is consistent across architecture, including x64, x86, and ARM.  The same assemblies and libraries can be imported and used on multiple platforms.  The assemblies and libraries are built using one of the.NET languages, C#, VB.NET, or F#. 3) Sharable. .NET Core uses one consistent API model written in.NET Standard that is common to all.NET applications.  The same API or library can be used with multiple platforms in multiple languages. SANGOLA COLLEGE SANGOLA 4|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO 4) Modern.  Unlike some older frameworks,.NET Core is designed to solve today's modern needs, including being mobile friendly, build once run everywhere, scalable, and high performance. .NET Core is designed to build applications that target all kinds of devices, including IoTs and gaming consoles. .NET Core supports modern language constructs with the help of C# version 8, like object-oriented and modular programming, generics, collections, lambdas, Language Integrated Query (LINQ), and asynchronous programming, which makes developers productive. 5) Fast. .NET Core 3.0 is fast. Compared to the.NET Framework. .NET Core is much quicker than other server-side frameworks such as Java Servlet and Node.js. According to a report published by TechEmpowers,.NET Core is much faster than any other framework. TechEmpower benchmark compares Web application frameworks for tasks such as database access for a single query, multiple queries, fortunes, data updates, plaintext, and JSON serialization. 6) Lightweight. .NET Core is lightweight. .NET Core can be included in your app or installed on a server side-by-side user, machine-wide, or. In addition, the.NET Core can be deployed in Docker containers. 7).NET Core is Friendly. .NET Core is compatible with.NET Framework, Xamarin, and Mono, via.NET Standard. .NET Core also supports working with various popular Web frameworks and libraries such as React, Angular, and JavaScript.  TypeScript is one of the key components of the.NET Core and Visual Studio ecosystem. *C# Basics- Introduction-  C# is a Pure Object Oriented Programming Language under.NET Framework developed by Microsoft.  C# is designed and developed by Anders Hejlsberg & his team members at Microsoft. C# Variables- Definition - A Variable is an identifier that denotes a storage location used to store data value. OR Variables are containers used to store data values. A variable may take different values at different time during the execution of program. SANGOLA COLLEGE SANGOLA 5|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO Variable naming conventions- 1. Variable name may consist of alphabet, digit and underscore 2. They must not begin with digit. 3. Uppercase and Lowercase are different/distinct i.e. the variable SUM is not same as Sum or sum. 4. It should not be Keyword. 5. White spaces is not allowed. Variable Declaration Syntax- ; Here, data type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable list may consist of one or more identifier names separated by commas. Some valid variable definitions are shown here − int i, j, k; char c, ch; float f, salary; double d; Initializing Variables Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is − = value; Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as − = value; Some examples are − int d = 3, f = 5; byte z = 22; double pi = 3.14159; char x = 'x'; Accepting Values from User The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable. For example, String name=Console.ReadLine(); int num; num = Convert.ToInt32(Console.ReadLine()); OR num=Int32.Parse (Console.ReadLine()); Note-The function Convert.ToInt32()/ Int32.Parse converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format. C# Data Types- Data type specify the size and type of values that can be stored. Every variable in C# is associated with a data type. SANGOLA COLLEGE SANGOLA 6|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO C# having rich set of data types. Characters Arrays, Delegates Value Types: In C#, Value Types are stored on the Stack and having Fixed Length. When a value of variable is assigned to another variable, the value is actually copied. It means that two identical copies of the value are available in memory. Reference Types: In C#, Reference Types are stored on the Heap and having variable (Not Fixed) Length. When a value of reference variable is assigned to another reference variable, the reference (address) is actually copied. It means that both variables are refers to same memory location. *Nullable types- In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable. The concept of Nullable type is useful when we deal with databases that contain elements that may not be assigned a value. C# provides two different ways to create Nullable types. 1. By creating System.Nullable instance, 2. By using ? operator 1. By creating System.Nullable instance Syntax: Nullable variable_name = null; Example internal class Program { static void Main(string[] args) { Nullable a= 10; Console.WriteLine("Value in a="+a); a = null; Console.WriteLine("Value in a=" + a); SANGOLA COLLEGE SANGOLA 7|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO Console.ReadKey(); } } 2. By using ? operator Syntax: datatype? variable_name = null; Example static void Main(string[] args) { int? a = 10; Console.WriteLine("Value in a="+a); a = null; Console.WriteLine("Value in a=" + a); Console.ReadKey(); } Note- A Nullable Type is incompatible with a General Data Type. This means we cannot operate between a nullable type and a general datatype. For example int? x = 4; int y = 3; int z = x * y; Console.WriteLine(z.ToString()); Console.ReadLine(); Here x is nullable while y is not nullable. So The above Program will generate the following compile time Error: Error 1 Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) *Null Coalescing Operator- The ?? operator is also known as the null-coalescing operator. null-coalescing Operator returns the left side operand if the operand is not null else if left side operand is NULL then it returns the right side operand. Example- static void Main(string[] args) { int? left = null;//NULL int right = 20; int? result = left ?? right; Console.WriteLine("Result="+result); Console.ReadKey(); SANGOLA COLLEGE SANGOLA 8|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO } Output- Result=20 Example:2- static void Main(string[] args) { int? left = 10;//NOT NULL int right = 20; int? result = left ?? right; Console.WriteLine("Result="+result); Console.ReadKey(); } Output- Result=10 Advantages/Usage of the Null-Coalescing Operator (??) operator.  It is used to define a default value for a nullable item (for both value types and reference types).  It prevents the runtime InvalidOperationException exception.  It helps us to remove many redundant "if-else" conditions.  It works for both reference types and value types.  The code becomes well-organized and readable. *Elvis Operator (?.) (Null Conditional Operator )- The null conditional operator (?.), often referred to as the "Elvis operator", allows you to perform member access or method calls on an object only if that object is not null. If the object is null, the operation returns null instead of throwing a null reference exception. This operator is a game-changer for developers, as it significantly reduces the amount of code needed to safely access members of potentially null objects. Example- class Employee { private string empname; public Employee(string nm) { empname = nm; } public string GetName() { return empname; } internal class Program { static void Main(string[] args) { Employee emp = new Employee("ABC"); SANGOLA COLLEGE SANGOLA 9|Page B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO Console.WriteLine(emp?.GetName()); Employee emp2 = null; Console.WriteLine(emp2?. GetName()); Console.ReadKey(); } } *Boxing and UnBoxing- Boxing is the process of converting a value type on stack in to the object type on heap. Boxing is implicit. A boxing conversion makes a copy of the value. So, changing the value of one variable will not impact others. Example: Boxing int i = 10; object ob = i; //performs boxing In the above example, the integer variable that is "i" is assigned to the object "ob". Thus the object data type is a reference type and base class of all the other classes in C# ultimately, an integer can be assigned to an object type. And this process of converting from the integer to the object data type is called boxing. Unboxing is the reverse of boxing. It is the process of converting a reference type to value type. Unboxing extract the value from the reference type and assign it to a value type. Unboxing is explicit. It means we have to cast explicitly. Example: Unboxing int i = 10; object ob = i; //performs boxing object ob = 10; int i = (int)ob; //performs unboxing Boxing Unboxing It convert value type into an object type. It convert an object type into value type. Boxing is an implicit conversion process. Unboxing is the explicit conversion process. Here, the value stored on the stack copied to Here, the object stored on the heap memory the object stored on the heap memory. copied to the value stored on the stack. C# Keywords- Keywords are predefined sets of reserved words that have special meaning in a program. SANGOLA COLLEGE SANGOLA 10 | P a g e B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO The meaning of keywords cannot be changed, neither can they be directly used as identifiers in a program. C# has a total of 79 keywords. All these keywords are in lowercase. Here is a complete list of all C# keywords. abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in in (generic modifier) int interface internal is lock long namespace new null object operator out out (generic modifier) override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using using static void volatile while Note- Although keywords are reserved words, they can be used as identifiers if @ is added as prefix. For example, int @void; The above statement will create a variable @void of type int. *Type Inference- Type inference refers to the automatic detection of the data type of an expression in a formal language. var keyword is used in C# to implement Type Inference. C# is a strongly typed language, and its default type declaration is explicit. This means we have to specify a type for a new variable or the compiler will throw an error. With version 3 of C#, a new keyword, var, was introduced that allows developers to store any type of value in an implicit way. This means that the compiler decides during compile time, when the first assignment happens, what the type will be for that variable. This can be easily integrated with LINQ. Syntax - var variablename = value; SANGOLA COLLEGE SANGOLA 11 | P a g e B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO internal class Program { static void Main(string[] args) { var nm='A'; var a = 10; var name = "XYZ"; Console.WriteLine(nm); Console.WriteLine(a); Console.WriteLine(name); Console.WriteLine(“DataType of nm=”+nm.GetType()); Console.WriteLine(“DataType of a=”+a.GetType()); Console.WriteLine(“DataType of name=”+name.GetType()); Console.ReadLine(); } } *Console Input Output- The Console class from the System namespace helps you with system I/O to the command prompt window or console. C# Output In order to output something in C#, we can use System.Console.WriteLine() OR System.Console.Write() Here, System is a namespace, Console is a class within namespace System and WriteLine and Write are methods of class Console. Difference between WriteLine() and Write() method The main difference between WriteLine() and Write() is that the Write() method only prints the string provided to it, while the WriteLine() method prints the string and moves to the start of next line as well. Ex. class Test { public static void Main(string[] args) { Console.WriteLine("Prints on "); Console.WriteLine("New line"); Console.Write("Prints on "); Console.Write("Same line"); } } } When we run the program, the output will be Prints on New line Prints on Same line SANGOLA COLLEGE SANGOLA 12 | P a g e B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO Combining (Concatenating) two strings using + operator and printing them Strings can be combined/concatenated using the + operator while printing. class Test { public static void Main(string[] args) { int val = 55; Console.WriteLine("Hello " + "World"); Console.WriteLine("Value = " + val); } } } When we run the program, the output will be Hello World Value = 55 Printing concatenated string using Formatted String [Better Alternative] A better alternative for printing concatenated string is using formatted string. Formatted string allows programmer to use placeholders for variables. For example, The following line, Console.WriteLine("Value = " + val); can be replaced by, Console.WriteLine("Value = {0}", val); {0} is the placeholder for variable val which will be replaced by value of val. Since only one variable is used so there is only one placeholder. Multiple variables can be used in the formatted string. We will see that in the example below. namespace Sample { class Test { public static void Main(string[] args) { int firstNumber = 5, secondNumber = 10, result; result = firstNumber + secondNumber; Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber, result); } } } When we run the program, the output will be 5 + 10 = 15 Here, {0} is replaced by firstNumber, {1} is replaced by secondNumber and {2} is replaced by result. This approach of printing output is more readable and less error prone than using + operator. SANGOLA COLLEGE SANGOLA 13 | P a g e B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO C# Input In C#, the simplest method to get input from the user is by using the ReadLine() method of the Console class. However, Read() and ReadKey() are also available for getting input from the user. They are also included in Console class. The difference between ReadLine(), Read() and ReadKey() method is:  ReadLine(): The ReadLine() method reads the next line of input from the standard input stream. It returns the same string.  Read(): The Read() method reads the next character from the standard input stream. It returns the ascii value of the character.  ReadKey(): The ReadKey() method obtains the next key pressed by user. This method is usually used to hold the screen until user press a key. *C# Operators- Operators in C# are symbols that are used to perform operations on operands. For example, consider the expression 2 + 3 = 5, here 2 and 3 are operands and + and = are called operators. So, the Operators in C# are used to manipulate the variables and values in a program. Types of Operators 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Conditional Operator 6. Special Operator In C#, the Operators can also be categorized based on the Number of Operands: 1. Unary Operator: The Operator that requires one operand (variable or value) to perform the operation is called Unary Operator.(Ex. i++,-9) 2. Binary Operator: Then Operator that requires two operands (variables or values) to perform the operation is called Binary Operator. (Ex. a+b) 3. Ternary Operator: The Operator that requires three operands (variables or values) to perform the operation is called Ternary Operator. Ternary Operator is also called Conditional Operator.( Ex. a>b?a:b) For a better understanding of the different types of operators supported in C# Programming Language, please have a look at the below image. SANGOLA COLLEGE SANGOLA 14 | P a g e B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO 1. Arithmetic Operators Arithmetic operators are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. C# Arithmetic Operators Operator Operator Name Example + Addition Operator 6 + 3 evaluates to 9 - Subtraction Operator 10 - 6 evaluates to 4 * Multiplication Operator 4 * 2 evaluates to 8 / Division Operator 10 / 5 evaluates to 2 % Modulo Operator (Remainder) 16 % 3 evaluates to 1 2. Relational Operators Relational operators are used to check the relationship between two operands. If the relationship is true the result will be true, otherwise it will result in false. Relational operators are used in decision making and loops. C# Relational Operators Operator Operator Name Example == Equal to 6 == 4 evaluates to false > Greater than 3 > -1 evaluates to true SANGOLA COLLEGE SANGOLA 15 | P a g e B.Sc. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO C# Relational Operators Operator Operator Name Example < Less than 5 < 3 evaluates to false >= Greater than or equal to 4 >= 4 evaluates to true = 10) { Console.WriteLine("x value greater than or equal to 10"); } else { Console.WriteLine("x value less than 10"); } } else { if (y

Use Quizgecko on...
Browser
Browser