├── .vscode
└── settings.json
├── Samples
├── SolidDemos
│ ├── OCP
│ │ ├── violation
│ │ │ ├── Shape.cs
│ │ │ ├── Circle.cs
│ │ │ ├── Rectangle.cs
│ │ │ └── AreaCalculator.cs
│ │ ├── correction
│ │ │ ├── Shape.cs
│ │ │ ├── Circle.cs
│ │ │ ├── Rectangle.cs
│ │ │ └── AreaCalculator.cs
│ │ ├── Program.cs
│ │ └── OCP.csproj
│ ├── DIP
│ │ ├── Program.cs
│ │ ├── DIP.csproj
│ │ ├── correction
│ │ │ └── CorrectOrder.cs
│ │ └── violation
│ │ │ └── Order.cs
│ ├── ISP
│ │ ├── Program.cs
│ │ ├── ISP.csproj
│ │ └── violation
│ │ │ └── IPaymentProcessor.cs
│ ├── LSP
│ │ ├── Program.cs
│ │ ├── violation
│ │ │ ├── Bird.cs
│ │ │ └── Penguin.cs
│ │ └── LSP.csproj
│ └── SRP
│ │ ├── Program.cs
│ │ ├── correction
│ │ ├── Customer.cs
│ │ └── CustomerRepository.cs
│ │ ├── SRP.csproj
│ │ └── violation
│ │ └── Customer.cs
├── OOPDemos
│ ├── Program.cs
│ └── OOPDemos.csproj
├── Pattern
│ ├── Program.cs
│ ├── Pattern.csproj
│ ├── AbstractFactory.cs
│ ├── Observer.cs
│ └── Mediator.cs
├── FoundationDemos
│ ├── FoundationDemos.csproj
│ ├── Example12.cs
│ ├── Example14.cs
│ ├── Program.cs
│ ├── Example8.cs
│ ├── Example4.cs
│ ├── Example2.cs
│ ├── Example10.cs
│ ├── Example6.cs
│ ├── Example1.cs
│ ├── Example9.cs
│ ├── Example5.cs
│ ├── Example7.cs
│ ├── Example3.cs
│ ├── Example13.cs
│ └── Example11.cs
└── Samples.sln
├── Presentations
└── solid.pptx
├── LICENSE
├── .gitignore
└── README.md
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "dotnet.defaultSolution": "Samples/Samples.sln"
3 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/violation/Shape.cs:
--------------------------------------------------------------------------------
1 | namespace OCP.violation;
2 |
3 | internal class Shape
4 | {
5 | }
--------------------------------------------------------------------------------
/Presentations/solid.pptx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/uguroney/C_Sharp_Fundamentals_Lecture_Note/HEAD/Presentations/solid.pptx
--------------------------------------------------------------------------------
/Samples/OOPDemos/Program.cs:
--------------------------------------------------------------------------------
1 | // See https://aka.ms/new-console-template for more information
2 | Console.WriteLine("Hello, World!");
3 |
--------------------------------------------------------------------------------
/Samples/Pattern/Program.cs:
--------------------------------------------------------------------------------
1 | // See https://aka.ms/new-console-template for more information
2 | Console.WriteLine("Hello, World!");
3 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/correction/Shape.cs:
--------------------------------------------------------------------------------
1 | namespace OCP.correction;
2 |
3 | internal abstract class Shape
4 | {
5 | public abstract double Area();
6 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/violation/Circle.cs:
--------------------------------------------------------------------------------
1 | namespace OCP.violation;
2 |
3 | internal class Circle : Shape
4 | {
5 | public double Radius { get; set; }
6 | }
7 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/DIP/Program.cs:
--------------------------------------------------------------------------------
1 | internal class Program
2 | {
3 | private static void Main(string[] args)
4 | {
5 | Console.WriteLine("Hello, World!");
6 | }
7 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/ISP/Program.cs:
--------------------------------------------------------------------------------
1 | internal class Program
2 | {
3 | private static void Main(string[] args)
4 | {
5 | Console.WriteLine("Hello, World!");
6 | }
7 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/LSP/Program.cs:
--------------------------------------------------------------------------------
1 | internal class Program
2 | {
3 | private static void Main(string[] args)
4 | {
5 | Console.WriteLine("Hello, World!");
6 | }
7 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/Program.cs:
--------------------------------------------------------------------------------
1 | internal class Program
2 | {
3 | private static void Main(string[] args)
4 | {
5 | Console.WriteLine("Hello, World!");
6 | }
7 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/SRP/Program.cs:
--------------------------------------------------------------------------------
1 | internal class Program
2 | {
3 | private static void Main(string[] args)
4 | {
5 | Console.WriteLine("Hello, World!");
6 | }
7 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/violation/Rectangle.cs:
--------------------------------------------------------------------------------
1 | namespace OCP.violation;
2 |
3 | internal class Rectangle : Shape
4 | {
5 | public double Width { get; set; }
6 | public double Height { get; set; }
7 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/SRP/correction/Customer.cs:
--------------------------------------------------------------------------------
1 | namespace SRP.correction;
2 |
3 | internal class Customer
4 | {
5 | public string? Name { get; set; }
6 | public string? Email { get; set; }
7 | }
8 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/LSP/violation/Bird.cs:
--------------------------------------------------------------------------------
1 | namespace LSP.violation;
2 |
3 | internal class Bird
4 | {
5 | public virtual void Fly()
6 | {
7 | Console.WriteLine("The bird is flying.");
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/correction/Circle.cs:
--------------------------------------------------------------------------------
1 | namespace OCP.correction;
2 |
3 | internal class Circle : Shape
4 | {
5 | public double Radius { get; set; }
6 |
7 | public override double Area()
8 | {
9 | return Math.PI * Radius * Radius;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/DIP/DIP.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | net7.0
5 | enable
6 | enable
7 |
8 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/ISP/ISP.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | net7.0
5 | enable
6 | enable
7 |
8 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/LSP/LSP.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | net7.0
5 | enable
6 | enable
7 |
8 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/OCP.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | net7.0
5 | enable
6 | enable
7 |
8 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/SRP/SRP.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | net7.0
5 | enable
6 | enable
7 |
8 |
--------------------------------------------------------------------------------
/Samples/OOPDemos/OOPDemos.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Samples/Pattern/Pattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/correction/Rectangle.cs:
--------------------------------------------------------------------------------
1 | namespace OCP.correction;
2 |
3 | internal class Rectangle : Shape
4 | {
5 | public double Width { get; set; }
6 | public double Height { get; set; }
7 |
8 | public override double Area()
9 | {
10 | return Width * Height;
11 | }
12 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/FoundationDemos.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net7.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/ISP/violation/IPaymentProcessor.cs:
--------------------------------------------------------------------------------
1 | namespace ISP.violation;
2 |
3 | public interface IPaymentProcessor
4 | {
5 | void ChargeCreditCard(decimal amount, string creditCardNumber, string expirationDate, string cvv);
6 | void ProcessPayPal(decimal amount, string payPalUsername, string payPalPassword);
7 |
8 | }
9 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/correction/AreaCalculator.cs:
--------------------------------------------------------------------------------
1 | namespace OCP.correction;
2 |
3 | internal class AreaCalculator
4 | {
5 | public double CalculateArea(Shape shape)
6 | {
7 | if(shape is null)
8 | throw new ArgumentNullException(nameof(shape));
9 | return shape.Area();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/LSP/violation/Penguin.cs:
--------------------------------------------------------------------------------
1 | namespace LSP
2 | {
3 | internal class Penguin : Bird
4 | {
5 | public override void Fly()
6 | {
7 | throw new NotImplementedException("Penguins cannot fly!!");
8 | }
9 | public override void Eat()
10 | {
11 | Console.WriteLine("The penguin is eating");
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example12.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains an example of using the var keyword in C#.
5 | ///
6 | public class Example12
7 | {
8 | public static void Run()
9 | {
10 | // Var keyword example
11 | var message = "Hello, world!";
12 | var number = 42;
13 | var pi = 3.14159;
14 |
15 | Console.WriteLine(message);
16 | Console.WriteLine(number);
17 | Console.WriteLine(pi);
18 | }
19 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example14.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains an example of using the null-coalescing operator.
5 | ///
6 | public class Example14
7 | {
8 | public static void Run()
9 | {
10 | // Null-coalescing operator example
11 | int? x = null;
12 | int y = x ?? 10;
13 |
14 | Console.WriteLine("y is: " + y);
15 |
16 | string s = null;
17 | string t = s ?? "default";
18 |
19 | Console.WriteLine("t is: " + t);
20 | }
21 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Program.cs:
--------------------------------------------------------------------------------
1 | using Samples;
2 |
3 | internal class Program
4 | {
5 | private static void Main(string[] args)
6 | {
7 | Example1.Run();
8 | Example2.Run();
9 | Example3.Run();
10 | Example4.Run();
11 | Example5.Run();
12 | Example6.Run();
13 | Example7.Run();
14 | Example8.Run();
15 | Example9.Run();
16 | Example10.Run();
17 | Example11.Run();
18 | Example12.Run();
19 | Example13.Run();
20 | Example14.Run();
21 | }
22 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/DIP/correction/CorrectOrder.cs:
--------------------------------------------------------------------------------
1 | namespace DIP.correction;
2 |
3 | public class Order{
4 |
5 | }
6 |
7 |
8 | public interface ILogger
9 | {
10 | void Log(string message);
11 | }
12 |
13 | public class OrderProcessor
14 | {
15 | private readonly ILogger _logger;
16 |
17 | public OrderProcessor(ILogger logger)
18 | {
19 | _logger = logger;
20 | }
21 |
22 | public void Process(Order order)
23 | {
24 | try
25 | {
26 | // process the order
27 | }
28 | catch (Exception ex)
29 | {
30 | _logger.Log(ex.Message);
31 | }
32 | }
33 | }
34 |
35 | public class DatabaseLogger : ILogger
36 | {
37 | public void Log(string message)
38 | {
39 | // log the message to a database
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/DIP/violation/Order.cs:
--------------------------------------------------------------------------------
1 | namespace DIP.violation;
2 |
3 | public class Order{
4 |
5 | }
6 |
7 | public class OrderProcessor
8 | {
9 | private readonly DatabaseLogger _logger;
10 |
11 | public OrderProcessor()
12 | {
13 | _logger = new DatabaseLogger(); // Violation: depending on a concrete implementation
14 | }
15 |
16 | public void Process(Order order)
17 | {
18 | try
19 | {
20 | // process the order
21 | }
22 | catch (Exception ex)
23 | {
24 | _logger.Log(ex.Message); // Violation: depending on a concrete implementation
25 | }
26 | }
27 | }
28 |
29 | public class DatabaseLogger
30 | {
31 | public void Log(string message)
32 | {
33 | // log the message to a database
34 | }
35 | }
36 |
37 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/SRP/violation/Customer.cs:
--------------------------------------------------------------------------------
1 | namespace SRP.violation;
2 |
3 | internal class Customer
4 | {
5 | public string Name { get; set; }
6 | public string Email { get; set; }
7 |
8 | public void Save()
9 | {
10 | try
11 | {
12 | using (var connection = new SqlConnection("Server=10.10.10.22;Database=DemoVs;User Id=sa;Password=rfvtgb45!!;"))
13 | {
14 | connection.Open();
15 | using (var command = new SqlCommand("INSERT INTO Customers (Name, Email) VALUES (@Name, @Email)", connection))
16 | {
17 | command.Parameters.AddWithValue("@Name", Name);
18 | command.Parameters.AddWithValue("@Email", Email);
19 | command.ExecuteNonQuery();
20 | }
21 | }
22 | }
23 | catch (Exception ex)
24 | {
25 | Console.WriteLine(ex.Message);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Samples/SolidDemos/OCP/violation/AreaCalculator.cs:
--------------------------------------------------------------------------------
1 | namespace OCP.violation;
2 |
3 | internal class AreaCalculator
4 | {
5 | public double CalculateArea(Shape shape)
6 | {
7 | if(shape == null)
8 | {
9 | throw new ArgumentNullException(nameof(shape));
10 | }
11 |
12 | if (shape is Rectangle)
13 | {
14 | var rectangle = shape as Rectangle;
15 | if(rectangle == null) throw new ArgumentException("Cannot cast shape to rectangle");
16 | return rectangle.Width * rectangle.Height;
17 | }
18 | else if (shape is Circle)
19 | {
20 | var circle = shape as Circle;
21 | if(circle == null) throw new ArgumentException("Cannot cast shape to circle");
22 | return Math.PI * circle.Radius * circle.Radius;
23 | }
24 | else
25 | {
26 | throw new ArgumentException("Shape type not supported.");
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example8.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains examples of different types of loops in C#.
5 | ///
6 | public class Example8
7 | {
8 | public static void Run()
9 | {
10 | // For loop example
11 | for (int i = 0; i < 5; i++)
12 | {
13 | Console.WriteLine("The value of i is: " + i);
14 | }
15 |
16 | // While loop example
17 | int j = 0;
18 | while (j < 5)
19 | {
20 | Console.WriteLine("The value of j is: " + j);
21 | j++;
22 | }
23 |
24 | // Do-while loop example
25 | int k = 0;
26 | do
27 | {
28 | Console.WriteLine("The value of k is: " + k);
29 | k++;
30 | } while (k < 5);
31 |
32 | // Foreach loop example
33 | int[] myArray = { 1, 2, 3, 4, 5 };
34 | foreach (int num in myArray)
35 | {
36 | Console.WriteLine("The value of num is: " + num);
37 | }
38 | }
39 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example4.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains examples of boxing, unboxing, and type casting in C#.
5 | ///
6 | public class Example4
7 | {
8 | public static void Run()
9 | {
10 | // Boxing example
11 | int myInt = 123;
12 | object myObject = myInt; // Boxing
13 | Console.WriteLine("My object value is: " + myObject);
14 |
15 | // Unboxing example
16 | int myInt2 = (int)myObject; // Unboxing
17 | Console.WriteLine("My integer value is: " + myInt2);
18 |
19 | // Type casting example
20 | double myDouble = 3.14;
21 | int myInt3 = (int)myDouble; // Explicit type casting
22 | Console.WriteLine("My integer value is: " + myInt3);
23 |
24 | // Implicit type casting example
25 | int myInt4 = 123;
26 | double myDouble2 = myInt4; // Implicit type casting
27 | Console.WriteLine("My double value is: " + myDouble2);
28 | }
29 | }
--------------------------------------------------------------------------------
/Samples/SolidDemos/SRP/correction/CustomerRepository.cs:
--------------------------------------------------------------------------------
1 | namespace SRP.correction;
2 |
3 | public class CustomerRepository
4 | {
5 | private readonly string connectionString;
6 |
7 | public CustomerRepository(string connectionString)
8 | {
9 | this.connectionString = connectionString;
10 | }
11 |
12 | public void Save(Customer customer)
13 | {
14 | try
15 | {
16 | using (var connection = new SqlConnection(connectionString))
17 | {
18 | connection.Open();
19 | using (var command = new SqlCommand("INSERT INTO Customers (Name, Email) VALUES (@Name, @Email)", connection))
20 | {
21 | command.Parameters.AddWithValue("@Name", customer.Name);
22 | command.Parameters.AddWithValue("@Email", customer.Email);
23 | command.ExecuteNonQuery();
24 | }
25 | }
26 | }
27 | catch (Exception ex)
28 | {
29 | Console.WriteLine(ex.Message);
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 ConstantMachine
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example2.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class demonstrates the usage of arithmetic, comparison, and logical operators in C#.
5 | ///
6 | public class Example2
7 | {
8 | public static void Run()
9 | {
10 | // Arithmetic operators
11 | int a = 10;
12 | int b = 5;
13 | Console.WriteLine("a + b = " + (a + b));
14 | Console.WriteLine("a - b = " + (a - b));
15 | Console.WriteLine("a * b = " + (a * b));
16 | Console.WriteLine("a / b = " + (a / b));
17 | Console.WriteLine("a % b = " + (a % b));
18 |
19 | // Comparison operators
20 | int c = 10;
21 | int d = 5;
22 | Console.WriteLine("c > d is " + (c > d));
23 | Console.WriteLine("c < d is " + (c < d));
24 | Console.WriteLine("c >= d is " + (c >= d));
25 | Console.WriteLine("c <= d is " + (c <= d));
26 | Console.WriteLine("c == d is " + (c == d));
27 | Console.WriteLine("c != d is " + (c != d));
28 |
29 | // Logical operators
30 | bool e = true;
31 | bool f = false;
32 | Console.WriteLine("e && f is " + (e && f));
33 | Console.WriteLine("e || f is " + (e || f));
34 | Console.WriteLine("!e is " + (!e));
35 | }
36 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example10.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// Provides examples for converting decimal, binary, and hexadecimal numbers.
5 | ///
6 | public class Example10
7 | {
8 | public static void Run()
9 | {
10 | // Decimal to binary example
11 | int decimalNumber = 10;
12 | string binaryNumber = Convert.ToString(decimalNumber, 2);
13 | Console.WriteLine("The binary representation of " + decimalNumber + " is: " + binaryNumber);
14 |
15 | // Binary to decimal example
16 | string binaryNumber2 = "1010";
17 | int decimalNumber2 = Convert.ToInt32(binaryNumber2, 2);
18 | Console.WriteLine("The decimal representation of " + binaryNumber2 + " is: " + decimalNumber2);
19 |
20 | // Decimal to hexadecimal example
21 | int decimalNumber3 = 255;
22 | string hexadecimalNumber = decimalNumber3.ToString("X");
23 | Console.WriteLine("The hexadecimal representation of " + decimalNumber3 + " is: " + hexadecimalNumber);
24 |
25 | // Hexadecimal to decimal example
26 | string hexadecimalNumber2 = "FF";
27 | int decimalNumber4 = int.Parse(hexadecimalNumber2, System.Globalization.NumberStyles.HexNumber);
28 | Console.WriteLine("The decimal representation of " + hexadecimalNumber2 + " is: " + decimalNumber4);
29 |
30 | }
31 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example6.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains examples of using the Console class to output text, read input, format output, change text color, and clear the console.
5 | ///
6 | public class Example6
7 | {
8 | public static void Run()
9 | {
10 | // Console output example
11 | Console.WriteLine("Hello, world!");
12 |
13 | // Console input example
14 | Console.Write("Enter your name: ");
15 | string name = Console.ReadLine();
16 | Console.WriteLine("Hello, " + name + "!");
17 |
18 | // Console formatting example
19 | int myInt = 123;
20 | double myDouble = 3.14;
21 | Console.WriteLine("My integer value is: {0}", myInt);
22 | Console.WriteLine("My double value is: {0:F2}", myDouble);
23 |
24 | // Console color example
25 | Console.ForegroundColor = ConsoleColor.Red;
26 | Console.WriteLine("This text is red.");
27 | Console.ResetColor();
28 |
29 | Console.Write("a = ");
30 | int a = int.Parse(Console.ReadLine());
31 | Console.Write("b = ");
32 | int b = int.Parse(Console.ReadLine());
33 | Console.WriteLine("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
34 | Console.Write("f = ");
35 | double f = double.Parse(Console.ReadLine()); Console.WriteLine("{0} * {1} / {2} = {3}",
36 | a, b, f, a * b / f);
37 |
38 | // Console clear example
39 | Console.Clear();
40 | }
41 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example1.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains examples of declaring and initializing different types of variables.
5 | ///
6 | public class Example1
7 | {
8 | public static void Run()
9 | {
10 | // Integer variable
11 | int myInt = 10;
12 | Console.WriteLine("My integer value is: " + myInt);
13 |
14 | // Double variable
15 | double myDouble = 3.14;
16 | Console.WriteLine("My double value is: " + myDouble);
17 |
18 | // Float variable
19 | float myFloat = 1.23f;
20 | Console.WriteLine("My float value is: " + myFloat);
21 |
22 | // Decimal variable
23 | decimal myDecimal = 123.45m;
24 | Console.WriteLine("My decimal value is: " + myDecimal);
25 |
26 | // Boolean variable
27 | bool myBool = true;
28 | Console.WriteLine("My boolean value is: " + myBool);
29 |
30 | // String variable
31 | string myString = "Hello, world!";
32 | Console.WriteLine("My string value is: " + myString);
33 |
34 | // Char variable
35 | char myChar = 'A';
36 | Console.WriteLine("My char value is: " + myChar);
37 |
38 | // Byte variable
39 | byte myByte = 255;
40 | Console.WriteLine("My byte value is: " + myByte);
41 |
42 | // Object variable
43 | object myObject = 123;
44 | Console.WriteLine("My object value is: " + myObject);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example9.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains examples of different types of arrays in C#.
5 | ///
6 | public class Example9
7 | {
8 | public static void Run()
9 | {
10 | // Single-dimensional array example
11 | int[] myArray = new int[5];
12 | myArray[0] = 1;
13 | myArray[1] = 2;
14 | myArray[2] = 3;
15 | myArray[3] = 4;
16 | myArray[4] = 5;
17 | Console.WriteLine("The value of the third element in myArray is: " + myArray[2]);
18 |
19 | // Multi-dimensional array example
20 | int[,] myMultiArray = new int[2, 3];
21 | myMultiArray[0, 0] = 1;
22 | myMultiArray[0, 1] = 2;
23 | myMultiArray[0, 2] = 3;
24 | myMultiArray[1, 0] = 4;
25 | myMultiArray[1, 1] = 5;
26 | myMultiArray[1, 2] = 6;
27 | Console.WriteLine("The value of the second element in the first row of myMultiArray is: " + myMultiArray[0, 1]);
28 |
29 | // Jagged array example
30 | int[][] myJaggedArray = new int[3][];
31 | myJaggedArray[0] = new int[] { 1, 2 };
32 | myJaggedArray[1] = new int[] { 3, 4, 5 };
33 | myJaggedArray[2] = new int[] { 6, 7, 8, 9 };
34 | Console.WriteLine("The value of the second element in the first row of myJaggedArray is: " + myJaggedArray[0][1]);
35 |
36 | // Array length example
37 | Console.WriteLine("The length of myArray is: " + myArray.Length);
38 |
39 | // Array sorting example
40 | int[] mySortedArray = myArray.OrderBy(x => x).ToArray();
41 | Console.WriteLine("The sorted values of myArray are: " + string.Join(", ", mySortedArray));
42 |
43 | // Array searching example
44 | int index = Array.IndexOf(myArray, 3);
45 | Console.WriteLine("The index of the value 3 in myArray is: " + index);
46 | }
47 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example5.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace Samples;
3 |
4 | ///
5 | /// This class contains examples of string manipulation in C#.
6 | ///
7 | public class Example5
8 | {
9 | public static void Run()
10 | {
11 | // String conversion example
12 | int myInt = 123;
13 | string myString = myInt.ToString();
14 | Console.WriteLine("My string value is: " + myString);
15 |
16 | // String concatenation example
17 | string firstName = "John";
18 | string lastName = "Doe";
19 | string fullName = firstName + " " + lastName;
20 | Console.WriteLine("My full name is: " + fullName);
21 |
22 | // String interpolation example
23 | int age = 30;
24 | string message = $"My name is {fullName} and I am {age} years old.";
25 | Console.WriteLine(message);
26 |
27 | // String length example
28 | string myString2 = "Hello, world!";
29 | int length = myString2.Length;
30 | Console.WriteLine("My string length is: " + length);
31 |
32 | // String indexing example
33 | char myChar = myString2[1];
34 | Console.WriteLine("My second character is: " + myChar);
35 |
36 | // String substring example
37 | string mySubstring = myString2.Substring(7, 5);
38 | Console.WriteLine("My substring is: " + mySubstring);
39 |
40 | // String replace example
41 | string myString3 = "Hello, world!";
42 | string myString4 = myString3.Replace("world", "C#");
43 | Console.WriteLine("My replaced string is: " + myString4);
44 |
45 | // String comparison example
46 | string myString5 = "Hello, world!";
47 | string myString6 = "hello, world!";
48 | bool isEqual = myString5.Equals(myString6, StringComparison.OrdinalIgnoreCase);
49 | Console.WriteLine("My strings are equal: " + isEqual);
50 | }
51 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example7.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// Contains examples of if statements and switch statements.
5 | ///
6 | public class Example7
7 | {
8 | public static void Run()
9 | {
10 | // If statement example
11 | int myInt = 10;
12 | if (myInt > 5)
13 | {
14 | Console.WriteLine("My integer is greater than 5.");
15 | }
16 |
17 | // If-else statement example
18 | int myInt2 = 3;
19 | if (myInt2 > 5)
20 | {
21 | Console.WriteLine("My integer is greater than 5.");
22 | }
23 | else
24 | {
25 | Console.WriteLine("My integer is less than or equal to 5.");
26 | }
27 |
28 | // If-else if-else statement example
29 | int myInt3 = 7;
30 | if (myInt3 > 10)
31 | {
32 | Console.WriteLine("My integer is greater than 10.");
33 | }
34 | else if (myInt3 > 5)
35 | {
36 | Console.WriteLine("My integer is greater than 5 but less than or equal to 10.");
37 | }
38 | else
39 | {
40 | Console.WriteLine("My integer is less than or equal to 5.");
41 | }
42 |
43 | // Ternary operator example
44 | int myInt4 = 8;
45 | string message = (myInt4 > 5) ? "My integer is greater than 5." : "My integer is less than or equal to 5.";
46 | Console.WriteLine(message);
47 |
48 | // Switch statement example
49 | int myInt5 = 2;
50 | switch (myInt5)
51 | {
52 | case 1:
53 | Console.WriteLine("My integer is 1.");
54 | break;
55 | case 2:
56 | Console.WriteLine("My integer is 2.");
57 | break;
58 | case 3:
59 | Console.WriteLine("My integer is 3.");
60 | break;
61 | default:
62 | Console.WriteLine("My integer is not 1, 2, or 3.");
63 | break;
64 | }
65 | }
66 | }
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example3.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains examples of arithmetic operations and operator precedence in C#.
5 | ///
6 | public class Example3
7 | {
8 | public static void Run()
9 | {
10 | int a = 10;
11 | int b = 5;
12 | int c = 2;
13 |
14 | int result1 = a + b * c;
15 | Console.WriteLine("a + b * c = " + result1);
16 |
17 | int result2 = (a + b) * c;
18 | Console.WriteLine("(a + b) * c = " + result2);
19 |
20 | int result3 = a / b * c;
21 | Console.WriteLine("a / b * c = " + result3);
22 |
23 | int result4 = a % b + c;
24 | Console.WriteLine("a % b + c = " + result4);
25 |
26 | int result5 = a + b++ * c;
27 | Console.WriteLine("a + b++ * c = " + result5);
28 | Console.WriteLine("b after increment = " + b);
29 |
30 | int result6 = a + ++b * c;
31 | Console.WriteLine("a + ++b * c = " + result6);
32 | Console.WriteLine("b after increment = " + b);
33 |
34 |
35 | int squarePerimeter = 17;
36 | double squareSide = squarePerimeter / 4.0; double squareArea = squareSide * squareSide;
37 | Console.WriteLine(squareSide); Console.WriteLine(squareArea);
38 |
39 |
40 | Console.WriteLine(a + b);
41 | Console.WriteLine(a + (b++));
42 | Console.WriteLine(a + b);
43 | Console.WriteLine(a + (++b));
44 | Console.WriteLine(a + b);
45 | Console.WriteLine(14 / a);
46 | Console.WriteLine(14 % a);
47 |
48 | int one = 1;
49 | int zero = 0;
50 |
51 | try{
52 | Console.WriteLine(one / zero);
53 | }
54 | catch (DivideByZeroException e)
55 | {
56 | Console.WriteLine(e.Message);
57 | }
58 |
59 | double dMinusOne = -1.0;
60 | double dZero = 0.0;
61 | try{
62 | Console.WriteLine(dMinusOne / dZero);
63 | }
64 | catch (DivideByZeroException e)
65 | {
66 | Console.WriteLine(e.Message);
67 | }
68 | }
69 | }
--------------------------------------------------------------------------------
/Samples/Samples.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.8.34004.107
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FoundationDemos", "FoundationDemos\FoundationDemos.csproj", "{779C57D4-66AC-485F-97BA-8178D572CA66}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OOPDemos", "OOPDemos\OOPDemos.csproj", "{E8B743C2-EC59-49EF-9B26-C85CCB9AACF8}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Pattern", "Pattern\Pattern.csproj", "{5363483F-389D-442B-8DA8-5BD21154BFCB}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {779C57D4-66AC-485F-97BA-8178D572CA66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {779C57D4-66AC-485F-97BA-8178D572CA66}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {779C57D4-66AC-485F-97BA-8178D572CA66}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {779C57D4-66AC-485F-97BA-8178D572CA66}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {E8B743C2-EC59-49EF-9B26-C85CCB9AACF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {E8B743C2-EC59-49EF-9B26-C85CCB9AACF8}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {E8B743C2-EC59-49EF-9B26-C85CCB9AACF8}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {E8B743C2-EC59-49EF-9B26-C85CCB9AACF8}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {5363483F-389D-442B-8DA8-5BD21154BFCB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {5363483F-389D-442B-8DA8-5BD21154BFCB}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {5363483F-389D-442B-8DA8-5BD21154BFCB}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {5363483F-389D-442B-8DA8-5BD21154BFCB}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {0AF9B30D-B903-469E-8F58-AFCD7CBA14DA}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example13.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// Contains examples of exception handling in C#.
5 | ///
6 | public class Example13
7 | {
8 | public static void Run()
9 | {
10 | try
11 | {
12 | // Exception handling example
13 | int[] numbers = { 1, 2, 3 };
14 | Console.WriteLine("The fourth number is: " + numbers[3]);
15 | }
16 | catch (IndexOutOfRangeException ex)
17 | {
18 | Console.WriteLine("An error occurred: " + ex.Message);
19 | }
20 | finally
21 | {
22 | Console.WriteLine("The program has finished executing.");
23 | }
24 |
25 | try
26 | {
27 | // Throw keyword example
28 | int age = -1;
29 | if (age < 0)
30 | {
31 | throw new ArgumentException("Age cannot be negative.");
32 | }
33 | Console.WriteLine("Age is: " + age);
34 | }
35 | catch (ArgumentException ex)
36 | {
37 | Console.WriteLine("An error occurred: " + ex.Message);
38 | }
39 | finally
40 | {
41 | Console.WriteLine("The program has finished executing.");
42 | }
43 |
44 | try
45 | {
46 | // Multiple catch and catch with when example
47 | int[] numbers = { 1, 2, 3 };
48 | Console.WriteLine("The fourth number is: " + numbers[3]);
49 | }
50 | catch (IndexOutOfRangeException ex)
51 | {
52 | Console.WriteLine("An index out of range error occurred: " + ex.Message);
53 | }
54 | catch (Exception ex) when (ex.Message.Contains("fourth"))
55 | {
56 | Console.WriteLine("A fourth element error occurred: " + ex.Message);
57 | }
58 | catch (Exception ex)
59 | {
60 | Console.WriteLine("An error occurred: " + ex.Message);
61 | }
62 | finally
63 | {
64 | Console.WriteLine("The program has finished executing.");
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/Samples/Pattern/AbstractFactory.cs:
--------------------------------------------------------------------------------
1 | namespace DoFactory.GangOfFour.Abstract.RealWorld
2 | {
3 |
4 |
5 | class MainApp
6 | {
7 |
8 |
9 | public static void Main()
10 | {
11 |
12 | ContinentFactory africa = new AfricaFactory();
13 | AnimalWorld world = new AnimalWorld(africa);
14 | world.RunFoodChain();
15 |
16 |
17 | ContinentFactory america = new AmericaFactory();
18 | world = new AnimalWorld(america);
19 | world.RunFoodChain();
20 |
21 |
22 | Console.ReadKey();
23 | }
24 | }
25 |
26 |
27 |
28 | abstract class ContinentFactory
29 | {
30 | public abstract Herbivore CreateHerbivore();
31 | public abstract Carnivore CreateCarnivore();
32 | }
33 |
34 |
35 |
36 | class AfricaFactory : ContinentFactory
37 | {
38 | public override Herbivore CreateHerbivore()
39 | {
40 | return new Wildebeest();
41 | }
42 | public override Carnivore CreateCarnivore()
43 | {
44 | return new Lion();
45 | }
46 | }
47 |
48 |
49 | class AmericaFactory : ContinentFactory
50 | {
51 | public override Herbivore CreateHerbivore()
52 | {
53 | return new Bison();
54 | }
55 | public override Carnivore CreateCarnivore()
56 | {
57 | return new Wolf();
58 | }
59 | }
60 |
61 |
62 |
63 | abstract class Herbivore
64 | {
65 | }
66 |
67 |
68 | abstract class Carnivore
69 | {
70 | public abstract void Eat(Herbivore h);
71 | }
72 |
73 |
74 |
75 | class Wildebeest : Herbivore
76 | {
77 | }
78 |
79 |
80 |
81 | class Lion : Carnivore
82 | {
83 | public override void Eat(Herbivore h)
84 | {
85 | Console.WriteLine(this.GetType().Name +
86 | " eats " + h.GetType().Name);
87 | }
88 | }
89 |
90 |
91 | class Bison : Herbivore
92 | {
93 | }
94 |
95 |
96 | class Wolf : Carnivore
97 | {
98 | public override void Eat(Herbivore h)
99 | {
100 | // Eat Bison
101 |
102 | Console.WriteLine(this.GetType().Name +
103 | " eats " + h.GetType().Name);
104 | }
105 | }
106 |
107 | class AnimalWorld
108 | {
109 | private Herbivore _herbivore;
110 | private Carnivore _carnivore;
111 |
112 |
113 | public AnimalWorld(ContinentFactory factory)
114 | {
115 | _carnivore = factory.CreateCarnivore();
116 | _herbivore = factory.CreateHerbivore();
117 | }
118 |
119 | public void RunFoodChain()
120 | {
121 | _carnivore.Eat(_herbivore);
122 | }
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/Samples/Pattern/Observer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System;
7 | using System.Collections.Generic;
8 |
9 | namespace Pattern
10 | {
11 | ///
12 | /// Observer Design Pattern
13 | ///
14 |
15 | public class Program
16 | {
17 | public static void Main(string[] args)
18 | {
19 | // Create IBM stock and attach investors
20 |
21 | IBM ibm = new IBM("IBM", 120.00);
22 | ibm.Attach(new Investor("Sorros"));
23 | ibm.Attach(new Investor("Berkshire"));
24 |
25 | // Fluctuating prices will notify investors
26 |
27 | ibm.Price = 120.10;
28 | ibm.Price = 121.00;
29 | ibm.Price = 120.50;
30 | ibm.Price = 120.75;
31 |
32 | // Wait for user
33 |
34 | Console.ReadKey();
35 | }
36 | }
37 |
38 | ///
39 | /// The 'Subject' abstract class
40 | ///
41 |
42 | public abstract class Stock
43 | {
44 | private string symbol;
45 | private double price;
46 | private List investors = new List();
47 |
48 | public Stock(string symbol, double price)
49 | {
50 | this.symbol = symbol;
51 | this.price = price;
52 | }
53 |
54 | public void Attach(IInvestor investor)
55 | {
56 | investors.Add(investor);
57 | }
58 |
59 | public void Detach(IInvestor investor)
60 | {
61 | investors.Remove(investor);
62 | }
63 |
64 | public void Notify()
65 | {
66 | foreach (IInvestor investor in investors)
67 | {
68 | investor.Update(this);
69 | }
70 |
71 | Console.WriteLine("");
72 | }
73 |
74 |
75 | public double Price
76 | {
77 | get { return price; }
78 | set
79 | {
80 | if (price != value)
81 | {
82 | price = value;
83 | Notify();
84 | }
85 | }
86 | }
87 |
88 |
89 | public string Symbol
90 | {
91 | get { return symbol; }
92 | }
93 | }
94 |
95 |
96 |
97 | public class IBM : Stock
98 | {
99 | // Constructor
100 |
101 | public IBM(string symbol, double price)
102 | : base(symbol, price)
103 | {
104 | }
105 | }
106 |
107 |
108 |
109 | public interface IInvestor
110 | {
111 | void Update(Stock stock);
112 | }
113 |
114 |
115 | public class Investor : IInvestor
116 | {
117 | private string name;
118 | private Stock stock;
119 |
120 |
121 | public Investor(string name)
122 | {
123 | this.name = name;
124 | }
125 |
126 | public void Update(Stock stock)
127 | {
128 | Console.WriteLine("Notified {0} of {1}'s " +
129 | "change to {2:C}", name, stock.Symbol, stock.Price);
130 | }
131 |
132 |
133 | public Stock Stock
134 | {
135 | get { return stock; }
136 | set { stock = value; }
137 | }
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/Samples/Pattern/Mediator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | using System;
8 | using System.Collections.Generic;
9 |
10 | namespace Mediator.RealWorld
11 | {
12 |
13 | public class Program
14 | {
15 | public static void Main(string[] args)
16 | {
17 | // Create chatroom
18 |
19 | Chatroom chatroom = new Chatroom();
20 |
21 | // Create participants and register them
22 |
23 | Participant George = new Beatle("George");
24 | Participant Paul = new Beatle("Paul");
25 | Participant Ringo = new Beatle("Ringo");
26 | Participant John = new Beatle("John");
27 | Participant Yoko = new NonBeatle("Yoko");
28 |
29 | chatroom.Register(George);
30 | chatroom.Register(Paul);
31 | chatroom.Register(Ringo);
32 | chatroom.Register(John);
33 | chatroom.Register(Yoko);
34 |
35 | // Chatting participants
36 |
37 | Yoko.Send("John", "Hi John!");
38 | Paul.Send("Ringo", "All you need is love");
39 | Ringo.Send("George", "My sweet Lord");
40 | Paul.Send("John", "Can't buy me love");
41 | John.Send("Yoko", "My sweet love");
42 |
43 | // Wait for user
44 |
45 | Console.ReadKey();
46 | }
47 | }
48 |
49 |
50 |
51 | public abstract class AbstractChatroom
52 | {
53 | public abstract void Register(Participant participant);
54 | public abstract void Send(
55 | string from, string to, string message);
56 | }
57 |
58 |
59 |
60 | public class Chatroom : AbstractChatroom
61 | {
62 | private Dictionary participants = new Dictionary();
63 |
64 | public override void Register(Participant participant)
65 | {
66 | if (!participants.ContainsValue(participant))
67 | {
68 | participants[participant.Name] = participant;
69 | }
70 |
71 | participant.Chatroom = this;
72 | }
73 |
74 | public override void Send(string from, string to, string message)
75 | {
76 | Participant participant = participants[to];
77 |
78 | if (participant != null)
79 | {
80 | participant.Receive(from, message);
81 | }
82 | }
83 | }
84 |
85 |
86 | public class Participant
87 | {
88 | Chatroom chatroom;
89 | string name;
90 |
91 |
92 | public Participant(string name)
93 | {
94 | this.name = name;
95 | }
96 |
97 |
98 | public string Name
99 | {
100 | get { return name; }
101 | }
102 |
103 |
104 | public Chatroom Chatroom
105 | {
106 | set { chatroom = value; }
107 | get { return chatroom; }
108 | }
109 |
110 |
111 | public void Send(string to, string message)
112 | {
113 | chatroom.Send(name, to, message);
114 | }
115 |
116 |
117 | public virtual void Receive(
118 | string from, string message)
119 | {
120 | Console.WriteLine("{0} to {1}: '{2}'",
121 | from, Name, message);
122 | }
123 | }
124 |
125 |
126 | public class Beatle : Participant
127 | {
128 |
129 | public Beatle(string name)
130 | : base(name)
131 | {
132 | }
133 |
134 | public override void Receive(string from, string message)
135 | {
136 | Console.Write("To a Beatle: ");
137 | base.Receive(from, message);
138 | }
139 | }
140 |
141 |
142 | public class NonBeatle : Participant
143 | {
144 | public NonBeatle(string name)
145 | : base(name)
146 | {
147 | }
148 |
149 | public override void Receive(string from, string message)
150 | {
151 | Console.Write("To a non-Beatle: ");
152 | base.Receive(from, message);
153 | }
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/Samples/FoundationDemos/Example11.cs:
--------------------------------------------------------------------------------
1 | namespace Samples;
2 |
3 | ///
4 | /// This class contains examples of different types of methods in C#.
5 | ///
6 | public class Example11
7 | {
8 | public static void Run()
9 | {
10 | // Method call example
11 | int result = AddNumbers(2, 3);
12 | Console.WriteLine("The result of adding 2 and 3 is: " + result);
13 |
14 | // Method overload example
15 | int result2 = AddNumbers(2, 3, 4);
16 | Console.WriteLine("The result of adding 2, 3, and 4 is: " + result2);
17 | // Void method call example
18 | PrintMessage("Hello, world!");
19 |
20 | // Void method with parameters example
21 | PrintSum(2, 3);
22 |
23 | // Recursive method call example
24 | int result3 = Factorial(5);
25 | Console.WriteLine("The factorial of 5 is: " + result3);
26 |
27 | // Pass by value example
28 | int x = 5;
29 | Console.WriteLine("Before calling PassByValue method, x = " + x);
30 | PassByValue(x);
31 | Console.WriteLine("After calling PassByValue method, x = " + x);
32 |
33 | // Pass by reference example
34 | int y = 5;
35 | Console.WriteLine("Before calling PassByRef method, y = " + y);
36 | PassByRef(ref y);
37 | Console.WriteLine("After calling PassByRef method, y = " + y);
38 |
39 | // Out method call example
40 | bool success = DivideNumbers(10, 2, out int result4);
41 | if (success)
42 | {
43 | Console.WriteLine("The result of dividing 10 by 2 is: " + result4);
44 | }
45 | else
46 | {
47 | Console.WriteLine("Division failed.");
48 | }
49 |
50 | // Params method call example
51 | int result5 = SumNumbers(1, 2, 3, 4, 5);
52 | Console.WriteLine("The sum of 1, 2, 3, 4, and 5 is: " + result5);
53 |
54 | // Yield method call example
55 | foreach (int number in GetNumbers())
56 | {
57 | Console.WriteLine(number);
58 | }
59 |
60 | }
61 |
62 | // Method definition example
63 | static int AddNumbers(int a, int b)
64 | {
65 | int sum = a + b;
66 | return sum;
67 | }
68 |
69 | // Method overload definition example
70 | static int AddNumbers(int a, int b, int c)
71 | {
72 | int sum = a + b + c;
73 | return sum;
74 | }
75 |
76 | // Void method definition example
77 | static void PrintMessage(string message)
78 | {
79 | Console.WriteLine(message);
80 | }
81 |
82 | // Void method with parameters definition example
83 | static void PrintSum(int a, int b)
84 | {
85 | int sum = a + b;
86 | Console.WriteLine("The sum of " + a + " and " + b + " is: " + sum);
87 | }
88 | // Recursive method definition example
89 | static int Factorial(int n)
90 | {
91 | if (n == 0)
92 | {
93 | return 1;
94 | }
95 | else
96 | {
97 | return n * Factorial(n - 1);
98 | }
99 | }
100 |
101 | // Pass by value method definition example
102 | static void PassByValue(int a)
103 | {
104 | a = 10;
105 | Console.WriteLine("Inside PassByValue method, a = " + a);
106 | }
107 |
108 | // Pass by reference method definition example
109 | static void PassByRef(ref int b)
110 | {
111 | b = 10;
112 | Console.WriteLine("Inside PassByRef method, b = " + b);
113 | }
114 |
115 | // Out method definition example
116 | static bool DivideNumbers(int a, int b, out int result)
117 | {
118 | if (b == 0)
119 | {
120 | result = 0;
121 | return false;
122 | }
123 | else
124 | {
125 | result = a / b;
126 | return true;
127 | }
128 | }
129 |
130 | // Params method definition example
131 | static int SumNumbers(params int[] numbers)
132 | {
133 | int sum = 0;
134 | foreach (int number in numbers)
135 | {
136 | sum += number;
137 | }
138 | return sum;
139 | }
140 | // Yield method definition example
141 | static IEnumerable GetNumbers()
142 | {
143 | yield return 1;
144 | yield return 2;
145 | yield return 3;
146 | yield return 4;
147 | yield return 5;
148 | }
149 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LecturesNotes
2 |
3 | [Discord Server](https://discord.gg/z2DgB27V)
4 |
5 | DotNet and C# lecture notes and samples
6 |
7 | ## 1. Introduction to Programming with .Net and C#
8 |
9 | ### 1.1. What is .NET?
10 |
11 | - .NET is a platform for building, deploying, and running Web Services and applications.
12 | - .NET Framework provides the necessary compile-time and run-time foundation to build and run any language that conforms to the Common Language Specification (CLS).
13 | - .NET Framework is a software framework developed by Microsoft that runs primarily on Microsoft Windows. It includes a large class library named Framework Class Library (FCL) and provides language interoperability (each language can use code written in other languages) across several programming languages. Programs written for .NET Framework execute in a software environment (as contrasted to hardware environment) named Common Language Runtime (CLR), an application virtual machine that provides services such as security, memory management, and exception handling. (As such, computer code written using .NET Framework is called "managed code".) FCL and CLR together constitute .NET Framework.
14 | - .NET Framework's Base Class Library provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. Programmers produce software by combining their own source code with .NET Framework and other libraries. .NET Framework is intended to be used by most new applications created for the Windows platform. Microsoft also produces an integrated development environment largely for .NET software called Visual Studio.
15 |
16 | ### 1.2. What is .Net 7.0?
17 |
18 | - .NET 7.0 is the next major release of .NET Core following 6.0. It will include new features and improvements for building high-performance, cross-platform web, cloud, and desktop applications with .NET. We'll continue to update this page with more details as we get closer to the release.
19 |
20 | ### 1.3. What is CLR?
21 |
22 | - The Common Language Runtime (CLR) is the virtual machine component of the .NET framework. It manages the execution of .NET programs and provides various useful services for those programs.
23 | - The CLR provides additional services including memory management, type safety, exception handling, garbage collection, security and thread management. All programs written for the .NET framework, regardless of programming language, are executed by the CLR. All versions of the .NET framework include CLR.
24 |
25 | ### 1.4. What is CTS?
26 |
27 | - The Common Type System (CTS) is a standard that specifies how type definitions and specific values of types are represented in computer memory. It is intended to allow programs written in different programming languages to easily share information. The CTS specification is owned and maintained by Microsoft. It is a constituent standard of Common Language Infrastructure (CLI).
28 |
29 | ### 1.5. What is IL?
30 |
31 | - Intermediate language (IL) is the language used in .NET. All .NET source code is compiled to IL. IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler. IL is similar to Java bytecode and is processed by the Common Language Runtime (CLR).
32 | - IL is a stack-based language (like the Java Virtual Machine (JVM)) that uses a stack to pass parameters to methods and to hold local variables. The stack is also used to evaluate expressions. IL is an object-oriented language that supports inheritance, interfaces, and polymorphism. It is also a structured language that supports loops, conditionals, and structured exception handling.
33 | - IL is a platform-independent language. The same IL code can be run on any system that has a .NET runtime installed. This is similar to Java bytecode, which can be run on any system that has a JVM installed.
34 |
35 | ### 1.6. What is JIT?
36 |
37 | - Just-in-time (JIT) compilation, also known as dynamic translation, is compilation done during execution of a program – at run time – rather than prior to execution. Most often this consists of translation to machine code, which is then executed directly, but can also refer to translation to another format.
38 | - A system implementing a JIT compiler typically continuously analyses the code being executed and identifies parts of the code where the speedup gained from compilation or recompilation would outweigh the overhead of compiling that code.
39 |
40 | ### 1.7. What is Lowering in C#?
41 |
42 | - Lowering is the process of converting a high-level language construct into a lower-level one. For example, a C# foreach loop is lowered into a while loop. The lowering process is performed by the compiler.
43 | - The lowering process is performed by the compiler. The compiler converts the C# code into IL code. The IL code is then converted into machine code by the JIT compiler.
44 |
45 | ### 1.8. What is Boxing and Unboxing?
46 |
47 | - Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.
48 | - Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.
49 |
50 | ### 1.9. What is Garbage Collection?
51 |
52 | - Garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program. Garbage collection was invented by John McCarthy around 1959 to solve the problems of manual memory management in his language Lisp. Garbage collection is essentially the opposite of manual memory management, which requires the programmer to specify which objects to deallocate and return to the memory system. Garbage collection is enabled by default in .NET Framework applications. It is also possible to explicitly control the lifetime of an object by implementing the IDisposable interface and manually freeing the object when finished with it. This is not required for memory management as the garbage collector will automatically free the object when it determines that the object is no longer reachable by the application.
53 |
54 | ### 1.10. What is Managed Code?
55 |
56 | - Managed code is computer program code that requires and will execute only under the management of a Common Language Runtime virtual machine (resulting in bytecode). It is contrasted with native code or machine code, which is produced by a compiler specific to the hardware architecture (CPU) in question, and run directly by the operating system. The term was coined by Microsoft as a buzzword in 2000 when they launched the .NET Framework to emphasize the fact that the code had to be managed by the common language runtime (CLR). The term is now used more widely, including for Java bytecode.
57 |
58 | ### 1.11. What is Unmanaged Code in C#?
59 |
60 | - Unmanaged code is code which is executed directly by the CPU. It is code that is not managed by the .NET Framework Common Language Runtime (CLR). Unmanaged code is typically written in a language such as C or C++. Unmanaged code is compiled to machine code. It is not compiled to IL code.
61 |
62 | ### 1.12. What is Strongly Typed Language?
63 |
64 | - A strongly typed language is a programming language that is more likely to generate errors if data does not closely match an expected type. Strong typing is a feature of many programming languages that enables more secure code by ensuring that data is in the expected format. Strongly typed languages include Java, C, C++, Ada, Delphi, Pascal, Haskell, ML, OCaml, Smalltalk, Swift, Rust, Scala, Common Lisp, Fortran, and Visual Basic .NET.
65 |
66 | ### 1.13. What is Weakly Typed Language?
67 |
68 | - A weakly typed language is a programming language that does not require a variable to be defined as a specific data type. Weak typing allows a variable to be initially assigned one data type and later re-assigned a value of a different type. Weakly typed languages include Perl, JavaScript, Visual Basic, and PHP.
69 |
70 | ## 2. Basic C# Syntax
71 |
72 | ### 2.1. What is C#?
73 |
74 | - C# (pronounced "C sharp") is a high-level, statically typed, multi-paradigm programming language developed by Microsoft. C# was designed by Anders Hejlsberg, and its development team is currently led by Mads Torgersen. C# is a general-purpose, object-oriented programming language. Its development team is led by Anders Hejlsberg. The most recent version is C# 11.0.
75 |
76 | ### 2.2. What is C# used for?
77 |
78 | - C# is used to develop web apps, desktop apps, mobile apps, games and much more. C# is a general-purpose programming language developed by Microsoft. C# can be used to create various types of applications, such as web, windows, console applications or other types of applications using Visual studio.
79 |
80 | ### 2.3. What is the difference between C# and .NET?
81 |
82 | - C# is a programming language. .NET is a framework. C# is a programming language. .NET is a framework that supports many programming languages. C# is one of the languages that .NET supports. C# is a programming language. .NET is a framework that supports many programming languages. C# is one of the languages that .NET supports.
83 |
84 | ### 2.4. C# Variables
85 |
86 | - A variable is a name given to a storage location that is used to store values of various data types. In C#, all the variables must be declared before use. The declaration of a variable is done by specifying the data type followed by the name of the variable. The syntax of declaring a variable is as follows −
87 |
88 | ```csharp
89 | ;
90 | ```
91 |
92 | - The following example declares a variable named counter of type int −
93 |
94 | ```csharp
95 | int counter;
96 | ```
97 |
98 | - The following example declares a variable named counter of type int and initializes it with value 0 −
99 |
100 | ```csharp
101 | int counter = 0;
102 | ```
103 |
104 | - The following example declares a variable named counter of type int and initializes it with value 0. The variable is declared as static, which means it is a class variable and not an instance variable −
105 |
106 | ```csharp
107 | static int counter = 0;
108 | ```
109 |
110 | - The following example declares a variable named counter of type int and initializes it with value 0. The variable is declared as static, which means it is a class variable and not an instance variable. The variable is also declared as readonly, which means it can be assigned a value only once −
111 |
112 | ```csharp
113 | static readonly int counter = 0;
114 | ```
115 |
116 | - The following example declares a variable named counter of type int and initializes it with value 0. The variable is declared as static, which means it is a class variable and not an instance variable. The variable is also declared as readonly, which means it can be assigned a value only once. The variable is also declared as volatile, which means it is a volatile variable −
117 |
118 | ```csharp
119 | static readonly volatile int counter = 0;
120 | ```
121 |
122 | - The following example declares a variable named counter of type int and initializes it with value 0. The variable is declared as static, which means it is a class variable and not an instance variable. The variable is also declared as readonly, which means it can be assigned a value only once. The variable is also declared as volatile, which means it is a volatile variable. The variable is also declared as unsafe, which means it is an unsafe variable −
123 |
124 | ```csharp
125 | static readonly volatile unsafe int counter = 0;
126 | ```
127 |
128 | - The following example declares a variable named counter of type int and initializes it with value 0. The variable is declared as static, which means it is a class variable and not an instance variable. The variable is also declared as readonly, which means it can be assigned a value only once. The variable is also declared as volatile, which means it is a volatile variable. The variable is also declared as unsafe, which means it is an unsafe variable. The variable is also declared as fixed, which means it is a fixed variable −
129 |
130 | ```csharp
131 | static readonly volatile unsafe fixed int counter = 0;
132 | ```
133 |
134 | - The following example declares a variable named counter of type int and initializes it with value 0. The variable is declared as static, which means it is a class variable and not an instance variable. The variable is also declared as readonly, which means it can be assigned a value only once. The variable is also declared as volatile, which means it is a volatile variable. The variable is also declared as unsafe, which means it is an unsafe variable. The variable is also declared as fixed, which means it is a fixed variable. The variable is also declared as extern, which means it is an external variable −
135 |
136 | ```csharp
137 | static readonly volatile unsafe fixed extern int counter = 0;
138 | ```
139 |
140 | - The following example declares a variable named counter of type int and initializes it with value 0. The variable is declared as static, which means it is a class variable and not an instance variable. The variable is also declared as readonly, which means it can be assigned a value only once. The variable is also declared as volatile, which means it is a volatile variable. The variable is also declared as unsafe, which means it is an unsafe variable. The variable is also declared as fixed, which means it is a fixed variable. The variable is also declared as extern, which means it is an external variable. The variable is also declared as const, which means it is a constant variable −
141 |
142 | ```csharp
143 | static readonly volatile unsafe fixed extern const int counter = 0;
144 | ```
145 |
146 | #### 2.4.1. C# Variable Types
147 |
148 | - C# supports the following types of variables −
149 | - Value types
150 | - Reference types
151 | - Pointer types
152 | - The following table lists the variable types −
153 | | Type | Description | Size | Range |
154 | | --- | --- | --- | --- |
155 | | bool | Represents a Boolean value. | 1 byte | True or false |
156 | | byte | Represents an unsigned byte. | 1 byte | 0 to 255 |
157 | | char | Represents a Unicode character. | 2 bytes | U +0000 to U +ffff |
158 | | decimal | Represents a decimal value. | 16 bytes | (+ or -)1.0 x 10e-28 to 7.9 x 10e28 |
159 | | double | Represents a double-precision floating-point value. | 8 bytes | (+ or -)5.0 x 10e-324 to 1.7 x 10e308 |
160 | | float | Represents a single-precision floating-point value. | 4 bytes | -3.4 x 10e38 to + 3.4 x 10e38 |
161 | | int | Represents a signed 32-bit integer. | 4 bytes | -2,147,483,648 to 2,147,483,647 |
162 | | long | Represents a signed 64-bit integer. | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
163 | | sbyte | Represents a signed byte. | 1 byte | -128 to 127 |
164 | | short | Represents a signed 16-bit integer. | 2 bytes | -32,768 to 32,767 |
165 | | uint | Represents an unsigned 32-bit integer. | 4 bytes | 0 to 4,294,967,295 |
166 | | ulong | Represents an unsigned 64-bit integer. | 8 bytes | 0 to 18,446,744,073,709,551,615 |
167 | | ushort | Represents an unsigned 16-bit integer. | 2 bytes | 0 to 65,535 |
168 |
169 | #### 2.4.2. C# Value Types
170 |
171 | - A value type holds the data within its own memory allocation. It means the variables of these data types directly contain values. The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value.
172 | - The following example declares a variable named counter of type int and initializes it with value 0 −
173 |
174 | ```csharp
175 | int counter = 0;
176 | ```
177 |
178 | #### 2.4.3. C# Reference Types
179 |
180 | - A reference type contains a pointer to another memory location that holds the data. Reference types don't store the value directly. Instead, they store the address where the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the data.
181 | - The following example declares a variable named counter of type object and initializes it with value 0 −
182 |
183 | ```csharp
184 | object counter = 0;
185 | ```
186 |
187 | #### 2.4.4. C# Pointer Types
188 |
189 | - A pointer is a variable that holds the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable. The pointer variables are declared using \* operator. However, the pointer variable must be declared before you can store any variable address in it. The general syntax of a pointer variable declaration is −
190 |
191 | ```csharp
192 | type *var-name;
193 | ```
194 |
195 | - Here, type is the pointer's base type; it must be a valid C# type and var-name is the name of the pointer variable. The asterisk \* used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −
196 |
197 | ```csharp
198 | int *ip; /* pointer to an integer */
199 | double *dp; /* pointer to a double */
200 | float *fp; /* pointer to a float */
201 | char *ch /* pointer to a character */
202 | ```
203 |
204 | - The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
205 |
206 | #### 2.4.5. C# Constants
207 |
208 | - Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well. Constants are treated just like regular variables except that their values cannot be modified after their definition.
209 | - The following example declares a constant named counter of type int and initializes it with value 0 −
210 |
211 | ```csharp
212 | const int counter = 0;
213 | ```
214 |
215 | #### 2.4.7. C# Modifiers
216 |
217 | - Modifiers are keywords that you add to those definitions to change their meanings. The C# language has the following modifiers −
218 | - Access Modifiers − default, public, protected, internal, private
219 | - Non-access Modifiers − abstract, sealed, static, unsafe, virtual, volatile, override
220 | - The following table lists the modifiers −
221 | | Modifier | Description |
222 | | --- | --- |
223 | |default|The default keyword is the default access modifier. If no access modifier is specified for a class, struct, interface, or member, then the default access modifier is used. The default access modifier for classes and structs is internal. The default access modifier for interfaces members is public. |
224 | |public|The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members. |
225 | |protected|The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances. |
226 | |internal|The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly. |
227 | |private|The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared. |
228 |
229 | ### 2.5. C# Operators
230 |
231 | - Operators are symbols that tell the compiler to perform specific mathematical or logical manipulations. C# language is rich in built-in operators and provides the following types of operators −
232 | - Arithmetic Operators
233 | - Relational Operators
234 | - Logical Operators
235 | - Bitwise Operators
236 | - Assignment Operators
237 | - Misc Operators
238 | - The following table lists the operators supported by the C# language −
239 | | Category | Operator | Description |
240 | | --- | --- | --- |
241 | | Arithmetic Operators | + | Adds two operands |
242 | | | - | Subtracts second operand from the first |
243 | | | _ | Multiplies both operands |
244 | | | / | Divides numerator by de-numerator |
245 | | | % | Modulus Operator and remainder of after an integer division |
246 | | | ++ | Increment operator increases integer value by one |
247 | | | -- | Decrement operator decreases integer value by one |
248 | | Relational Operators | == | Checks if the values of two operands are equal or not, if yes then condition becomes true. |
249 | | | != | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. |
250 | | | > | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
251 | | | < | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
252 | | | >= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
253 | | | <= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
254 | | Logical Operators | && | Called Logical AND operator. If both the operands are non-zero, then condition becomes true. |
255 | | | \|\| | Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. |
256 | | | ! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. |
257 | | Bitwise Operators | & | Binary AND Operator copies a bit to the result if it exists in both operands. |
258 | | | \| | Binary OR Operator copies a bit if it exists in either operand. |
259 | | | ^ | Binary XOR Operator copies the bit if it is set in one operand but not both. |
260 | | | ~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. |
261 | | | << | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. |
262 | | | >> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. |
263 | | Assignment Operators | = | Simple assignment operator, Assigns values from right side operands to left side operand |
264 | | | += | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand |
265 | | | -= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand |
266 | | | _= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand |
267 | | | /= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand |
268 | | | %= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand |
269 | | | <<= | Left shift AND assignment operator |
270 | | | >>= | Right shift AND assignment operator |
271 | | | &= | Bitwise AND assignment operator |
272 | | | ^= | bitwise exclusive OR and assignment operator |
273 | | | \|= | bitwise inclusive OR and assignment operator |
274 | | Misc Operators | sizeof | Returns the size of a data type |
275 | | | typeof | Returns the type of a class |
276 | | | & | Returns the address of a variable |
277 |
278 | ### 2.6. C# Decision Making
279 |
280 | - Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
281 |
282 | #### 2.6.1. C# if Statement
283 |
284 | - An if statement consists of a Boolean expression followed by one or more statements.
285 | - Syntax
286 |
287 | ```csharp
288 | if(Boolean_expression) {
289 | /* statement(s) will execute if the Boolean expression is true */
290 | }
291 | ```
292 |
293 | - If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If not, the first set of code after the end of the if statement (after the closing curly brace) will be executed.
294 | - The following example demonstrates the if statement −
295 |
296 | ```csharp
297 | int x = 10;
298 | if(x < 20) {
299 | Console.WriteLine("x is less than 20");
300 | }
301 | ```
302 |
303 | #### 2.6.2. C# if...else Statement
304 |
305 | - An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
306 | - Syntax
307 |
308 | ```csharp
309 | if(Boolean_expression) {
310 | /* Executes when the Boolean expression is true */
311 | } else {
312 | /* Executes when the Boolean expression is false */
313 | }
314 | ```
315 |
316 | - If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.
317 | - The following example demonstrates the if...else statement −
318 |
319 | ```csharp
320 | int x = 30;
321 | if(x < 20) {
322 | Console.WriteLine("x is less than 20");
323 | } else {
324 | Console.WriteLine("x is greater than 20");
325 | }
326 | ```
327 |
328 | #### 2.6.3. C# nested if...else Statement
329 |
330 | - You can use one if or else if statement inside another if or else if statement(s).
331 | - Syntax
332 |
333 | ```csharp
334 | if(Boolean_expression 1) {
335 | /* Executes when the Boolean expression 1 is true */
336 | if(Boolean_expression 2) {
337 | /* Executes when the Boolean expression 2 is true */
338 | }
339 | }
340 | ```
341 |
342 | - If the Boolean expression 1 evaluates to true, then the block of code inside the if statement will be executed. If Boolean expression 1 evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.
343 | - If Boolean expression 1 evaluates to true and Boolean expression 2 evaluates to false, then the block of code inside the else statement will be executed.
344 | - The following example demonstrates the nested if...else statement −
345 |
346 | ```csharp
347 | int x = 30;
348 | int y = 10;
349 | if(x == 30) {
350 | if(y == 10) {
351 | Console.WriteLine("X = 30 and Y = 10");
352 | }
353 | }
354 | ```
355 |
356 | #### 2.6.4. C# switch Statement
357 |
358 | - A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
359 | - Syntax
360 |
361 | ```csharp
362 | switch(expression) {
363 | case constant-expression :
364 | statement(s);
365 | break; /* optional */
366 | case constant-expression :
367 | statement(s);
368 | break; /* optional */
369 |
370 | /* you can have any number of case statements */
371 | default : /* Optional */
372 | statement(s);
373 | }
374 | ```
375 |
376 | - The following rules apply to a switch statement −
377 | - The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
378 | - You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
379 | - The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
380 | - When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
381 | - When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
382 | - Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
383 | - A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
384 | - The following example demonstrates the switch statement −
385 |
386 | ```csharp
387 | char grade = 'B';
388 | switch(grade) {
389 | case 'A' :
390 | Console.WriteLine("Excellent!");
391 | break;
392 | case 'B' :
393 | case 'C' :
394 | Console.WriteLine("Well done");
395 | break;
396 | case 'D' :
397 | Console.WriteLine("You passed");
398 | break;
399 | case 'F' :
400 | Console.WriteLine("Better try again");
401 | break;
402 | default :
403 | Console.WriteLine("Invalid grade");
404 | break;
405 | }
406 | Console.WriteLine("Your grade is {0}", grade);
407 | ```
408 |
409 | - When the above code is compiled and executed, it produces the following result −
410 |
411 | ```csharp
412 | Well done
413 | Your grade is B
414 | ```
415 |
416 | #### 2.6.5. C# nested switch Statement
417 |
418 | - You can use one switch statement inside another switch statement(s).
419 | - Syntax
420 |
421 | ```csharp
422 | switch(ch1) {
423 | case 'A':
424 | Console.WriteLine("This A is part of outer switch");
425 | switch(ch2) {
426 | case 'A':
427 | Console.WriteLine("This A is part of inner switch");
428 | break;
429 | case 'B': /* no break statement in this case */
430 | Console.WriteLine("This B is part of inner switch");
431 | break;
432 | }
433 | break;
434 | case 'B': /* no break statement in this case */
435 | Console.WriteLine("This B is part of outer switch");
436 | break;
437 | }
438 | ```
439 |
440 | #### 2.6.6. C# if...else if...else Statement
441 |
442 | - An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
443 | - When using if, else if, else statements there are few points to keep in mind −
444 | - An if can have zero or one else's and it must come after any else if's.
445 | - An if can have zero to many else if's and they must come before the else.
446 | - Once an else if succeeds, none of the remaining else if's or else's will be tested.
447 | - Syntax
448 |
449 | ```csharp
450 | if(Boolean_expression 1) {
451 | /* Executes when the Boolean expression 1 is true */
452 | } else if( Boolean_expression 2) {
453 | /* Executes when the Boolean expression 2 is true */
454 | } else if( Boolean_expression 3) {
455 | /* Executes when the Boolean expression 3 is true */
456 | } else {
457 | /* Executes when the none of the above condition is true */
458 | }
459 | ```
460 |
461 | - The following example demonstrates the if...else if...else statement −
462 |
463 | ```csharp
464 | int x = 30;
465 | if( x == 10 ) {
466 | Console.WriteLine("Value of x is 10");
467 | } else if( x == 20 ) {
468 | Console.WriteLine("Value of x is 20");
469 | } else if( x == 30 ) {
470 | Console.WriteLine("Value of x is 30");
471 | } else {
472 | Console.WriteLine("None of the values is matching");
473 | }
474 | ```
475 |
476 | - When the above code is compiled and executed, it produces the following result −
477 |
478 | ```csharp
479 | Value of x is 30
480 | ```
481 |
482 | ### 2.7. C# Loops
483 |
484 | - Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. In programming, loops are used to repeat a block of code until a specified condition is met.
485 | - C# provides following types of loops to handle looping requirements. Click the following links to check their detail.
486 | - while loop
487 | - for loop
488 | - do...while loop
489 | - nested loops
490 | - The following table lists the loop control statements supported by C# language −
491 | | Control Statement | Description |
492 | | --- | --- |
493 | | break statement | Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. |
494 | | continue statement | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
495 | | goto statement | Transfers control to the labeled statement. NEVER USE|
496 | | return statement | Terminates the execution of a method and returns control to the calling method. |
497 |
498 | #### 2.7.1. C# while Loop
499 |
500 | - A while loop statement repeatedly executes a target statement as long as a given condition is true.
501 | - Syntax
502 |
503 | ```csharp
504 | while(condition) {
505 | statement(s);
506 | }
507 | ```
508 |
509 | - Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
510 | - When the condition becomes false, program control passes to the line immediately following the loop.
511 | - The following example demonstrates the while loop −
512 |
513 | ```csharp
514 | int a = 10;
515 | while(a < 15) {
516 | Console.WriteLine("value of a: {0}", a);
517 | a++;
518 | }
519 | ```
520 |
521 | - When the above code is compiled and executed, it produces the following result −
522 |
523 | ```csharp
524 | value of a: 10
525 | value of a: 11
526 | value of a: 12
527 | value of a: 13
528 | value of a: 14
529 | ```
530 |
531 | #### 2.7.2. C# for Loop
532 |
533 | - A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
534 | - Syntax
535 |
536 | ```csharp
537 | for(initialization; condition; increment) {
538 | statement(s);
539 | }
540 | ```
541 |
542 | - Here is the flow of control in a for loop −
543 | - The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
544 | - Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
545 | - After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
546 | - The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
547 | - The following example demonstrates the for loop −
548 |
549 | ```csharp
550 | for(int a = 10; a < 15; a = a + 1) {
551 | Console.WriteLine("value of a: {0}", a);
552 | }
553 | ```
554 |
555 | - When the above code is compiled and executed, it produces the following result −
556 |
557 | ```csharp
558 | value of a: 10
559 | value of a: 11
560 | value of a: 12
561 | value of a: 13
562 | value of a: 14
563 | ```
564 |
565 | #### 2.7.3. C# do...while Loop
566 |
567 | - A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
568 | - Syntax
569 |
570 | ```csharp
571 | do {
572 | statement(s);
573 | } while( condition );
574 | ```
575 |
576 | - Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
577 | - If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.
578 | - The following example demonstrates the do...while loop −
579 |
580 | ```csharp
581 | int a = 10;
582 | do {
583 | Console.WriteLine("value of a: {0}", a);
584 | a = a + 1;
585 | } while(a < 15);
586 | ```
587 |
588 | - When the above code is compiled and executed, it produces the following result −
589 |
590 | ```csharp
591 | value of a: 10
592 | value of a: 11
593 | value of a: 12
594 | value of a: 13
595 | value of a: 14
596 | ```
597 |
598 | #### 2.7.4. C# nested loops
599 |
600 | - C# allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
601 | - Syntax
602 |
603 | ```csharp
604 | for(initialization; condition; increment) {
605 | for(initialization; condition; increment) {
606 | statement(s);
607 | }
608 | statement(s);
609 | }
610 | ```
611 |
612 | - The following example demonstrates the nested loop −
613 |
614 | ```csharp
615 | for(int a = 1; a <= 3; a++) {
616 | for(int b = 1; b <= 3; b++) {
617 | Console.WriteLine("value of a: {0}, value of b: {1}", a, b);
618 | }
619 | }
620 | ```
621 |
622 | - When the above code is compiled and executed, it produces the following result −
623 |
624 | ```csharp
625 | value of a: 1, value of b: 1
626 | value of a: 1, value of b: 2
627 | value of a: 1, value of b: 3
628 | value of a: 2, value of b: 1
629 | value of a: 2, value of b: 2
630 | value of a: 2, value of b: 3
631 | value of a: 3, value of b: 1
632 | value of a: 3, value of b: 2
633 | value of a: 3, value of b: 3
634 | ```
635 |
636 | ### 2.8. C# Arrays
637 |
638 | - An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
639 | - Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
640 | - All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
641 | - The following example declares an array of integers named numbers, initializes the array with three values, and prints the array values to the console −
642 |
643 | ```csharp
644 | int[] numbers = new int[3];
645 | numbers[0] = 1;
646 | numbers[1] = 2;
647 | numbers[2] = 3;
648 | Console.WriteLine(numbers[0]);
649 | Console.WriteLine(numbers[1]);
650 | Console.WriteLine(numbers[2]);
651 | ```
652 |
653 | - When the above code is compiled and executed, it produces the following result −
654 |
655 | ```csharp
656 | 1
657 | 2
658 | 3
659 | ```
660 |
661 | #### 2.8.1. C# Array Types
662 |
663 | - C# provides many data types. However, each variable in C# must be a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
664 | - C# provides the following types of arrays −
665 | - Single Dimensional Array
666 | - Multidimensional Array
667 | - Jagged Array
668 | - The following table lists the important properties of the Array class −
669 | | Property | Description |
670 | | --- | --- |
671 | | IsFixedSize | Gets a value indicating whether the Array has a fixed size. |
672 | | IsReadOnly | Gets a value indicating whether the Array is read-only. |
673 | | Length | Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array. |
674 | | LongLength | Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array. |
675 | | Rank | Gets the rank (number of dimensions) of the Array. |
676 | | SyncRoot | Gets an object that can be used to synchronize access to the Array. |
677 |
678 | #### 2.8.2. C# Single Dimensional Array
679 |
680 | - A single-dimensional array is a sequential list of items. Each item is assigned a unique index value. The following example declares a single-dimensional array of five integers −
681 |
682 | ```csharp
683 | int[] numbers = new int[5];
684 | ```
685 |
686 | - The following example declares a single-dimensional array of five integers and initializes the second element in the array with value 10 −
687 |
688 | ```csharp
689 | int[] numbers = new int[5];
690 | numbers[1] = 10;
691 | ```
692 |
693 | - The following example declares a single-dimensional array of five integers and initializes the array with values 1, 2, 3, 4, and 5 −
694 |
695 | ```csharp
696 | int[] numbers = new int[5] {1, 2, 3, 4, 5};
697 | ```
698 |
699 | - The following example declares a single-dimensional array of five integers and initializes the array with values 1, 2, 3, 4, and 5. The size of the array is determined by the number of values provided between braces and separated by commas −
700 |
701 | ```csharp
702 | int[] numbers = new int[] {1, 2, 3, 4, 5};
703 | ```
704 |
705 | #### 2.8.3. C# Multidimensional Array
706 |
707 | - A multidimensional array is an array containing one or more arrays. C# supports multidimensional arrays that contain two or three dimensions.
708 | - The following example declares a two-dimensional array of four rows and two columns −
709 |
710 | ```csharp
711 | int[,] numbers = new int[4, 2];
712 | ```
713 |
714 | - The following example declares a two-dimensional array of four rows and two columns and initializes the array with the values 1, 2, 3, and 4 −
715 |
716 | ```csharp
717 | int[,] numbers = new int[4, 2] { {0, 0}, {1, 2}, {2, 4}, {3, 6} };
718 | ```
719 |
720 | - The following example declares a two-dimensional array of four rows and two columns and initializes the array with the values 1, 2, 3, and 4. The size of the array is determined by the number of values provided between braces and separated by commas −
721 |
722 | ```csharp
723 | int[,] numbers = new int[,] { {0, 0}, {1, 2}, {2, 4}, {3, 6} };
724 | ```
725 |
726 | #### 2.8.4. C# Jagged Array
727 |
728 | - A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null. The following example declares a jagged array of three rows and initializes the first row with three integers, the second row with two integers, and the third row with one integer −
729 |
730 | ```csharp
731 | int[][] numbers = new int[3][];
732 | numbers[0] = new int[3] {1, 2, 3};
733 | numbers[1] = new int[2] {4, 5};
734 | numbers[2] = new int[1] {6};
735 | ```
736 |
737 | ### 2.9. C# Strings
738 |
739 | - A string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0').
740 | - The String class provides members for comparing strings, testing strings for equality, finding characters or substrings in a string, modifying a string, extracting substrings from a string, combining strings, formatting values, copying a string, and normalizing a string.
741 | - C# strings are immutable. This means that once a string is created, it is not possible to modify it. However, you can perform various operation on a string −
742 | - String Length
743 | - String Concatenation
744 | - String Format
745 | - String Escape Characters
746 | - Verbatim String
747 | - String Methods
748 | - The following example demonstrates the various operations on a string −
749 |
750 | ````csharp
751 |
752 | string fname, lname;
753 | fname = "Jane";
754 | lname = "Doe";
755 |
756 | string fullname = fname + lname;
757 | Console.WriteLine("Full Name: {0}", fullname);
758 |
759 | string fullname2 = string.Concat(fname, lname);
760 | Console.WriteLine("Full Name: {0}", fullname2);
761 |
762 | string[] sarray = new string[3];
763 | sarray[0] = "Hello";
764 | sarray[1] = "From";
765 | sarray[2] = "World";
766 |
767 | string message = string.Join(" ", sarray);
768 | Console.WriteLine("Message: {0}", message);
769 |
770 | ### 2.10. C# Structures
771 | - A structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
772 | - The following example demonstrates how to use structure in a program −
773 | ```csharp
774 |
775 | struct Books {
776 | public string title;
777 | public string author;
778 | public string subject;
779 | public int book_id;
780 | };
781 |
782 | public static void Main(string[] args) {
783 | Books Book1; /* Declare Book1 of type Book */
784 | Books Book2; /* Declare Book2 of type Book */
785 |
786 | /* book 1 specification */
787 | Book1.title = "C Programming";
788 | Book1.author = "Nuha Ali";
789 | Book1.subject = "C Programming Tutorial";
790 | Book1.book_id = 6495407;
791 |
792 | /* book 2 specification */
793 | Book2.title = "Telecom Billing";
794 | Book2.author = "Zara Ali";
795 | Book2.subject = "Telecom Billing Tutorial";
796 | Book2.book_id = 6495700;
797 |
798 | /* print Book1 info */
799 | Console.WriteLine( "Book 1 title : {0}", Book1.title);
800 | Console.WriteLine("Book 1 author : {0}", Book1.author);
801 | Console.WriteLine("Book 1 subject : {0}", Book1.subject);
802 | Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
803 |
804 | /* print Book2 info */
805 | Console.WriteLine("Book 2 title : {0}", Book2.title);
806 | Console.WriteLine("Book 2 author : {0}", Book2.author);
807 | Console.WriteLine("Book 2 subject : {0}", Book2.subject);
808 | Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
809 | Console.ReadKey();
810 | }
811 | ````
812 |
813 | ### 2.11. C# Enums
814 |
815 | - An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration.
816 | - By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
817 | - The following example shows how to use enums in a program −
818 |
819 | ```csharp
820 | enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
821 |
822 | class Program {
823 | static void Main(string[] args) {
824 | int WeekdayStart = (int)Days.Mon;
825 | int WeekdayEnd = (int)Days.Fri;
826 | Console.WriteLine("Monday: {0}", WeekdayStart);
827 | Console.WriteLine("Friday: {0}", WeekdayEnd);
828 | Console.ReadKey();
829 | }
830 | }
831 | ```
832 |
833 | ### 2.11.1. C# Enums Flags
834 |
835 | - The FlagsAttribute indicates that an enumeration can be treated as a bit field; that is, a set of flags.
836 | - The following example shows how to use enums flags in a program −
837 |
838 | ```csharp
839 |
840 | [Flag]
841 | enum Days { Sun = 1, Mon = 2, Tue = 4, Wed = 8, Thu = 16, Fri = 32, Sat = 64 };
842 |
843 | class Program {
844 | static void Main(string[] args) {
845 | Days workingDays = Days.Mon | Days.Tue | Days.Wed | Days.Thu | Days.Fri;
846 | Console.WriteLine(workingDays);
847 | Console.ReadKey();
848 | }
849 | }
850 | ```
851 |
852 | ### 2.12. C# Preprocessors
853 |
854 | - The C# preprocessor directives are used to provide additional information to the compiler to help in compilation of the code. The compiler directives begin with # symbol. The C# preprocessor does not have a separate preprocessor, but the directives are processed as if there was one.
855 | - The following table lists the preprocessor directives −
856 | | Directive | Description |
857 | | --- | --- |
858 | | #define | Defines a sequence of characters, called symbol. |
859 | | #undef | Undefines a symbol. |
860 | | #if | Evaluates a symbol or symbols. |
861 | | #else | Specifies an alternative for #if directive. |
862 | | #elif | Specifies a new condition if the previous condition was false. |
863 | | #endif | Specifies the end of #if directive. |
864 | | #line | Lets you modify the compiler's line number and (optionally) the file name output for errors and warnings. |
865 | | #error | Generates a compiler error when the specified conditional directive evaluates to true. |
866 | | #warning | Generates a compiler warning when the specified conditional directive evaluates to true. |
867 | | #region | Lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor. |
868 | | #endregion | Marks the end of a #region block. |
869 |
870 | ### 2.13. C# Namespaces
871 |
872 | - Namespaces are used to organize your program into a hierarchy of logical groups. The using keyword is used for including the namespaces in the program. The namespaces in C# are used to organize too many classes so that it can be easy to handle the application.
873 | - The following example demonstrates how to use namespaces in a program −
874 |
875 | ```csharp
876 | using System;
877 |
878 | namespace first_space {
879 | class namespace_cl {
880 | public void func() {
881 | Console.WriteLine("Inside first_space");
882 | }
883 | }
884 | }
885 |
886 | namespace second_space {
887 | class namespace_cl {
888 | public void func() {
889 | Console.WriteLine("Inside second_space");
890 | }
891 | }
892 | }
893 |
894 | class TestClass {
895 | static void Main(string[] args) {
896 | first_space.namespace_cl fc = new first_space.namespace_cl();
897 | second_space.namespace_cl sc = new second_space.namespace_cl();
898 | fc.func();
899 | sc.func();
900 | Console.ReadKey();
901 | }
902 | }
903 | ```
904 |
905 | ### 2.14. C# Functions
906 |
907 | - A function is a group of statements that together perform a task. Every C# program has at least one function, which is Main(), and all the most trivial programs can define additional functions.
908 | - You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is such that each function performs a specific task.
909 | - A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
910 | - The C# standard library provides numerous built-in functions that your program can call. For example, function Console.WriteLine() to print a message on the console.
911 | - To use a function, you will have to call that function to perform the defined task.
912 | - Following is the syntax to define a function in C# −
913 |
914 | ```csharp
915 | return_type function_name( parameter list ) {
916 | body of the function
917 | }
918 | ```
919 |
920 | #### 2.14.1. C# Function Parameters
921 |
922 | - Parameters are used to pass values or variable references to methods. The parameters are declared in the method declaration. The parameters are always passed by value. However, if you want to pass a parameter by reference, then you need to use the ref keyword.
923 | - The following example demonstrates how to use parameters in a function −
924 |
925 | ```csharp
926 | using System;
927 |
928 | namespace CalculatorApplication {
929 | public static void Add(int a, int b)
930 | {
931 | int sum = a + b;
932 | Console.WriteLine("Sum of {0} and {1} is {2}", a, b, sum);
933 | Console.ReadKey();
934 | }
935 |
936 | public static void Main(string[] args)
937 | {
938 | int a = 10;
939 | int b = 20;
940 | Add(a, b);
941 | }
942 | }
943 | ```
944 |
945 | #### 2.14.2. C# Function Return Values
946 |
947 | - A function can return a value to the class that called it. You use the return keyword for this purpose. The type of value that your function returns must match the return type of the function as declared in the function definition.
948 | - The following example demonstrates how to use return values in a function −
949 |
950 | ```csharp
951 | using System;
952 |
953 | namespace CalculatorApplication {
954 | public static int Add(int a, int b)
955 | {
956 | int sum = a + b;
957 | return sum;
958 | }
959 |
960 | public static void Main(string[] args)
961 | {
962 | int a = 10;
963 | int b = 20;
964 | int sum = Add(a, b);
965 | Console.WriteLine("Sum of {0} and {1} is {2}", a, b, sum);
966 | Console.ReadKey();
967 | }
968 | }
969 | ```
970 |
971 | #### 2.14.3. C# Function Scope
972 |
973 | - The scope of a variable is the part of the program that can refer to that variable by name. Variables declared inside a function are not accessible from outside the function. Hence, they have a local scope.
974 | - The following example demonstrates how to use scope in a function −
975 |
976 | ```csharp
977 | using System;
978 |
979 | namespace CalculatorApplication {
980 | public static void Add(int a, int b)
981 | {
982 | int sum = a + b;
983 | Console.WriteLine("Sum of {0} and {1} is {2}", a, b, sum);
984 | Console.ReadKey();
985 | }
986 |
987 | public static void Main(string[] args)
988 | {
989 | int a = 10;
990 | int b = 20;
991 | Add(a, b);
992 | Console.WriteLine("Sum of {0} and {1} is {2}", a, b, sum);
993 | }
994 | }
995 | ```
996 |
997 | #### 2.14.4. C# Function Recursion
998 |
999 | - Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.
1000 | - The following example demonstrates how to use recursion in a function −
1001 |
1002 | ```csharp
1003 | using System;
1004 |
1005 | namespace CalculatorApplication {
1006 | public static int factorial(int num)
1007 | {
1008 | /* local variable declaration */
1009 | int result;
1010 |
1011 | if (num == 1)
1012 | {
1013 | return 1;
1014 | }
1015 | else
1016 | {
1017 | result = factorial(num - 1) * num;
1018 | return result;
1019 | }
1020 | }
1021 |
1022 | public static void Main(string[] args)
1023 | {
1024 | Console.WriteLine(factorial(6));
1025 | Console.WriteLine(factorial(7));
1026 | Console.WriteLine(factorial(8));
1027 | Console.ReadKey();
1028 | }
1029 | }
1030 | ```
1031 |
1032 | #### 2.14.5. C# Function Optional Parameters
1033 |
1034 | - C# allows you to assign default values to function parameters. If the function is called without passing value for these parameters, the default value gets assigned to the parameter.
1035 | - The following example demonstrates how to use optional parameters in a function −
1036 |
1037 | ```csharp
1038 | using System;
1039 |
1040 | namespace CalculatorApplication {
1041 | public static int Add(int a = 1, int b = 2)
1042 | {
1043 | int sum = a + b;
1044 | return sum;
1045 | }
1046 |
1047 | public static void Main(string[] args)
1048 | {
1049 | int sum = Add(10, 20);
1050 | Console.WriteLine("Sum: {0}", sum);
1051 | Console.ReadKey();
1052 | }
1053 | }
1054 | ```
1055 |
1056 | #### 2.14.6. C# Function Named Arguments
1057 |
1058 | - C# allows you to pass arguments to a function in a named form. While calling the function, you can specify the argument name along with the value. This way, you can make the arguments to function more meaningful.
1059 | - The following example demonstrates how to use named arguments in a function −
1060 |
1061 | ```csharp
1062 | using System;
1063 |
1064 | namespace CalculatorApplication {
1065 | public static int Add(int num1, int num2)
1066 | {
1067 | int sum = num1 + num2;
1068 | return sum;
1069 | }
1070 |
1071 | public static void Main(string[] args)
1072 | {
1073 | int sum = Add(num2: 20, num1: 10);
1074 | Console.WriteLine("Sum: {0}", sum);
1075 | Console.ReadKey();
1076 | }
1077 | }
1078 | ```
1079 |
1080 | #### 2.14.7. C# Function Overloading
1081 |
1082 | - C# allows you to define two or more functions with the same name, but with different parameters. This concept is known as function overloading and is quite useful in many situations.
1083 | - The following example demonstrates how to use function overloading in a program −
1084 |
1085 | ```csharp
1086 | using System;
1087 |
1088 | namespace CalculatorApplication {
1089 | public static int Add(int num1, int num2)
1090 | {
1091 | return num1 + num2;
1092 | }
1093 |
1094 | public static int Add(int num1, int num2, int num3)
1095 | {
1096 | return num1 + num2 + num3;
1097 | }
1098 |
1099 | public static void Main(string[] args)
1100 | {
1101 | Console.WriteLine(Add(10, 20));
1102 | Console.WriteLine(Add(10, 20, 30));
1103 | Console.ReadKey();
1104 | }
1105 | }
1106 | ```
1107 |
1108 | #### 2.14.8. C# Function Params
1109 |
1110 | - C# allows you to pass a variable number of arguments to a function. The params keyword is used to specify a parameter array which allows you to pass an arbitrary number of arguments to a function.
1111 | - The following example demonstrates how to use params in a function −
1112 |
1113 | ```csharp
1114 | using System;
1115 |
1116 | namespace CalculatorApplication {
1117 | public static int Add(params int[] arr)
1118 | {
1119 | int sum = 0;
1120 | foreach (int i in arr)
1121 | {
1122 | sum += i;
1123 | }
1124 | return sum;
1125 | }
1126 |
1127 | public static void Main(string[] args)
1128 | {
1129 | Console.WriteLine(Add(1, 2, 3, 4, 5));
1130 | Console.WriteLine(Add(10, 20, 30));
1131 | Console.ReadKey();
1132 | }
1133 | }
1134 | ```
1135 |
1136 | #### 2.14.9. C# Function ref Keyword
1137 |
1138 | - C# allows you to pass a variable by reference to a function. The ref keyword is used for this purpose. The ref keyword passes the reference of a variable in the memory to the function.
1139 | - The following example demonstrates how to use ref in a function −
1140 |
1141 | ```csharp
1142 | using System;
1143 |
1144 | namespace CalculatorApplication {
1145 | public static void Swap(ref int x, ref int y)
1146 | {
1147 | int temp;
1148 |
1149 | temp = x;
1150 | x = y;
1151 | y = temp;
1152 | }
1153 |
1154 | public static void Main(string[] args)
1155 | {
1156 | int a = 100;
1157 | int b = 200;
1158 |
1159 | Console.WriteLine("Before swap, value of a : {0}", a);
1160 | Console.WriteLine("Before swap, value of b : {0}", b);
1161 |
1162 | Swap(ref a, ref b);
1163 |
1164 | Console.WriteLine("After swap, value of a : {0}", a);
1165 | Console.WriteLine("After swap, value of b : {0}", b);
1166 |
1167 | Console.ReadKey();
1168 | }
1169 | }
1170 | ```
1171 |
1172 | #### 2.14.10. C# Function out Keyword
1173 |
1174 | - C# allows you to return a value through a parameter of the function. The out keyword is used for this purpose. The out keyword passes the reference of a variable in the memory to the function.
1175 | - The following example demonstrates how to use out in a function −
1176 |
1177 | ```csharp
1178 | using System;
1179 |
1180 | namespace CalculatorApplication {
1181 | public static void getValue(out int x)
1182 | {
1183 | int temp = 5;
1184 | x = temp;
1185 | }
1186 |
1187 | public static void Main(string[] args)
1188 | {
1189 | int a = 100;
1190 |
1191 | Console.WriteLine("Before method call, value of a : {0}", a);
1192 | getValue(out a);
1193 | Console.WriteLine("After method call, value of a : {0}", a);
1194 |
1195 | Console.ReadKey();
1196 | }
1197 | }
1198 | ```
1199 |
1200 | #### 2.14.11. C# Function In Keyword
1201 |
1202 | - C# allows you to pass a variable by reference to a function. The in keyword is used for this purpose. The in keyword passes the reference of a variable in the memory to the function.
1203 | - The following example demonstrates how to use in in a function −
1204 |
1205 | ```csharp
1206 | using System;
1207 |
1208 | namespace CalculatorApplication {
1209 | public static void getValue(in int x)
1210 | {
1211 | Console.WriteLine("Value of x: {0}", x);
1212 | }
1213 |
1214 | public static void Main(string[] args)
1215 | {
1216 | int a = 100;
1217 |
1218 | Console.WriteLine("Before method call, value of a : {0}", a);
1219 | getValue(in a);
1220 | Console.WriteLine("After method call, value of a : {0}", a);
1221 |
1222 | Console.ReadKey();
1223 | }
1224 | }
1225 | ```
1226 |
1227 | #### 2.14.12. C# Function Delegates
1228 |
1229 | - A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.
1230 | - You can invoke (or call) the method through the delegate instance.
1231 | - Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs. The following example demonstrates how to use delegates in a program −
1232 |
1233 | ```csharp
1234 | using System;
1235 |
1236 | namespace CalculatorApplication {
1237 | public delegate int NumberChanger(int n);
1238 |
1239 | class TestDelegate {
1240 | static int num = 10;
1241 |
1242 | public static int AddNum(int p)
1243 | {
1244 | num += p;
1245 | return num;
1246 | }
1247 |
1248 | public static int MultNum(int q)
1249 | {
1250 | num *= q;
1251 | return num;
1252 | }
1253 |
1254 | public static int getNum()
1255 | {
1256 | return num;
1257 | }
1258 |
1259 | public static void Main(string[] args)
1260 | {
1261 | //create delegate instances
1262 | NumberChanger nc1 = new NumberChanger(AddNum);
1263 | NumberChanger nc2 = new NumberChanger(MultNum);
1264 |
1265 | //calling the methods using the delegate objects
1266 | nc1(25);
1267 | Console.WriteLine("Value of Num: {0}", getNum());
1268 | nc2(5);
1269 | Console.WriteLine("Value of Num: {0}", getNum());
1270 | Console.ReadKey();
1271 | }
1272 | }
1273 | }
1274 | ```
1275 |
1276 | #### 2.14.13. C# Function Anonymous Methods
1277 |
1278 | - Anonymous methods are the methods without a name, just the body. The anonymous methods can be assigned to a delegate variable of compatible signature.
1279 | - The following example demonstrates how to use anonymous methods in a program −
1280 |
1281 | ```csharp
1282 | using System;
1283 |
1284 | namespace CalculatorApplication {
1285 | public delegate void Print(int value);
1286 |
1287 | class TestDelegate {
1288 | static void Main(string[] args)
1289 | {
1290 | // Print delegate points to PrintNumber
1291 | Print printDel = PrintNumber;
1292 |
1293 | printDel(100000);
1294 | printDel(200);
1295 |
1296 | // Print delegate points to PrintMoney
1297 | printDel = PrintMoney;
1298 |
1299 | printDel(10000);
1300 | printDel(20000);
1301 |
1302 | Console.ReadKey();
1303 | }
1304 |
1305 | public static void PrintNumber(int num)
1306 | {
1307 | Console.WriteLine("Number: {0,-12:N0}", num);
1308 | }
1309 |
1310 | public static void PrintMoney(int money)
1311 | {
1312 | Console.WriteLine("Money: {0:C}", money);
1313 | }
1314 | }
1315 | }
1316 | ```
1317 |
1318 | #### 2.14.14. C# Operator Overloading
1319 |
1320 | - C# allows you to specify the meaning of operators when applied to instances of a class or struct. This ability is called operator overloading. Operator overloading is syntactic sugar for a function call.
1321 | - The following example demonstrates how to use operator overloading in a program −
1322 |
1323 | ```csharp
1324 | using System;
1325 |
1326 | public static int operator +(int a, int b)
1327 | {
1328 | return a + b;
1329 | }
1330 |
1331 | class TestOperator {
1332 | static void Main(string[] args)
1333 | {
1334 | int a = 10;
1335 | int b = 20;
1336 | int c;
1337 |
1338 | c = a + b;
1339 | Console.WriteLine("c = {0}", c);
1340 | Console.ReadKey();
1341 | }
1342 | }
1343 | ```
1344 |
1345 | #### 2.14.15. C# Function Extension Methods
1346 |
1347 | - C# allows you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. This process is called extending a type.
1348 | - The following example demonstrates how to use extension methods in a program −
1349 |
1350 | ```csharp
1351 | using System;
1352 |
1353 | namespace ExtensionMethodApplication {
1354 | public static class MyExtension {
1355 | public static int Sub(this int i, int j)
1356 | {
1357 | return i - j;
1358 | }
1359 | }
1360 |
1361 | class ExtensionDemo {
1362 | static void Main(string[] args)
1363 | {
1364 | int i = 10;
1365 | int j = 15;
1366 | int k = i.Sub(j);
1367 | Console.WriteLine("i - j = {0}", k);
1368 | Console.ReadKey();
1369 | }
1370 | }
1371 | }
1372 | ```
1373 |
1374 | #### 2.14.16. C# Function Lambda Expressions
1375 |
1376 | - Lambda expressions are anonymous functions. These functions are mostly used as arguments to other functions. The lambda expression is mostly used to create delegates in LINQ.
1377 | - The following example demonstrates how to use lambda expressions in a program −
1378 |
1379 | ```csharp
1380 | using System;
1381 |
1382 | namespace LambdaExpressionApplication {
1383 | class Test {
1384 | static void Main(string[] args)
1385 | {
1386 | // lambda expression
1387 | Func square = x => x * x;
1388 |
1389 | // invoke delegate and print the output
1390 | Console.WriteLine(square(5));
1391 | Console.ReadKey();
1392 | }
1393 | }
1394 | }
1395 | ```
1396 |
1397 | #### 2.14.17. C# Events
1398 |
1399 | - An event is a notification sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic.
1400 | - The object that raises the event is called the event sender. The event sender doesn't know which object or method will receive (handle) the events it raises. The event is typically a member of the event sender; for example, the Click event is a member of the Button class, and the PropertyChanged event is a member of the Employee class.
1401 | - The following example demonstrates how to use events in a program −
1402 |
1403 | ```csharp
1404 | using System;
1405 |
1406 | namespace CalculatorApplication {
1407 | public delegate string MyDel(string str);
1408 |
1409 | class EventProgram {
1410 | event MyDel MyEvent;
1411 |
1412 | public EventProgram()
1413 | {
1414 | this.MyEvent += new MyDel(this.WelcomeUser);
1415 | }
1416 |
1417 | public string WelcomeUser(string username)
1418 | {
1419 | return "Welcome " + username;
1420 | }
1421 |
1422 | static void Main(string[] args)
1423 | {
1424 | EventProgram obj1 = new EventProgram();
1425 | string result = obj1.MyEvent("Tutorials Point");
1426 | Console.WriteLine(result);
1427 | }
1428 | }
1429 | }
1430 | ```
1431 |
1432 | ### 2.15. C# Nullable Types
1433 |
1434 | - C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
1435 | - For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable variable.
1436 | - The following example demonstrates how to use nullable types in a program −
1437 |
1438 | ```csharp
1439 | using System;
1440 |
1441 | namespace CalculatorApplication {
1442 | class NullablesAtShow {
1443 | static void Main(string[] args)
1444 | {
1445 | int? num1 = null;
1446 | int? num2 = 45;
1447 |
1448 | double? num3 = new double?();
1449 | double? num4 = 3.14157;
1450 |
1451 | bool? boolval = new bool?();
1452 |
1453 | // display the values
1454 | Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}",
1455 | num1, num2, num3, num4);
1456 | Console.WriteLine("A Nullable boolean value: {0}", boolval);
1457 | Console.ReadLine();
1458 | }
1459 | }
1460 | }
1461 | ```
1462 |
1463 | ### 2.16. C# Dynamic Types (USE WITH CAUTION)
1464 |
1465 | - C# provides another data type called dynamic type. The dynamic type variables are similar to object type variables. The difference between object and dynamic types is that the object type variables are resolved at compile time, whereas the dynamic type variables are resolved at run time.
1466 |
1467 | #### 2.16.1. C# Dynamic Type Variables
1468 |
1469 | - The dynamic type variables are declared with the keyword dynamic. The following example demonstrates how to use dynamic type variables in a program −
1470 |
1471 | ```csharp
1472 |
1473 | using System;
1474 |
1475 | namespace CalculatorApplication {
1476 | class DynamicTest {
1477 | static void Main(string[] args)
1478 | {
1479 | dynamic d = 20; // d is dynamic type
1480 | Console.WriteLine(d);
1481 | Console.WriteLine(d.GetType());
1482 |
1483 | d = "A string here"; // d is still dynamic type
1484 | Console.WriteLine(d);
1485 | Console.WriteLine(d.GetType());
1486 |
1487 | Console.ReadKey();
1488 | }
1489 | }
1490 | }
1491 | ```
1492 |
1493 | ### 2.17. C# var Keyword
1494 |
1495 | - The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.
1496 | - The following example demonstrates how to use var keyword in a program −
1497 |
1498 | ```csharp
1499 | using System;
1500 |
1501 | namespace CalculatorApplication {
1502 | class VarTest {
1503 | static void Main(string[] args)
1504 | {
1505 | var i = 5;
1506 | var s = "Hello World";
1507 | Console.WriteLine("i: {0}, s: {1}", i, s);
1508 | }
1509 | }
1510 | }
1511 | ```
1512 |
1513 | ### 2.18. C# Constants
1514 |
1515 | - Constants are expressions with a fixed value. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
1516 | - Constants are treated just like regular variables except that their values cannot be modified after their definition.
1517 | - The following example demonstrates how to use constants in a program −
1518 |
1519 | ```csharp
1520 | using System;
1521 |
1522 | namespace CalculatorApplication {
1523 | class Program {
1524 | static void Main(string[] args)
1525 | {
1526 | const double pi = 3.14159;
1527 | double r;
1528 | Console.WriteLine("Enter Radius: ");
1529 | r = Convert.ToDouble(Console.ReadLine());
1530 | double areaCircle = pi * r * r;
1531 | Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
1532 | Console.ReadLine();
1533 | }
1534 | }
1535 | }
1536 | ```
1537 |
1538 | ### 2.19 C# Statics
1539 |
1540 | - The static keyword is used to declare a static member. If we declare a static member, it belongs to the type itself rather than to a specific object. It means that only one instance of a static member exists, even if you create multiple instances of the class. It will be shared by all objects.
1541 | - The following example demonstrates how to use statics in a program −
1542 |
1543 | ```csharp
1544 | using System;
1545 |
1546 | namespace CalculatorApplication {
1547 | class StaticVar {
1548 | public static int num;
1549 | public void count()
1550 | {
1551 | num++;
1552 | }
1553 | public int getNum()
1554 | {
1555 | return num;
1556 | }
1557 | }
1558 |
1559 | class StaticTester {
1560 | static void Main(string[] args)
1561 | {
1562 | StaticVar s = new StaticVar();
1563 | s.count();
1564 | s.count();
1565 | s.count();
1566 | Console.WriteLine("Variable num: {0}", s.getNum());
1567 | Console.ReadKey();
1568 | }
1569 | }
1570 | }
1571 | ```
1572 |
1573 | ### 2.20 C# Exception Handling
1574 |
1575 | - When a program encounters a situation that it cannot handle, it throws an exception. An exception is a runtime error that can occur when there is a problem in code. Exception handling enables a program to deal with runtime errors and continue its normal flow of operations.
1576 | - The following example demonstrates how to use exception handling in a program −
1577 |
1578 | ```csharp
1579 | using System;
1580 |
1581 | namespace CalculatorApplication {
1582 | class DivNumbers {
1583 | int result;
1584 |
1585 | DivNumbers()
1586 | {
1587 | result = 0;
1588 | }
1589 |
1590 | public void division(int num1, int num2)
1591 | {
1592 | try
1593 | {
1594 | result = num1 / num2;
1595 | }
1596 | catch (DivideByZeroException e)
1597 | {
1598 | Console.WriteLine("Exception caught: {0}", e);
1599 | }
1600 | finally
1601 | {
1602 | Console.WriteLine("Result: {0}", result);
1603 | }
1604 | }
1605 |
1606 | static void Main(string[] args)
1607 | {
1608 | DivNumbers d = new DivNumbers();
1609 | d.division(25, 0);
1610 | Console.ReadKey();
1611 | }
1612 | }
1613 | }
1614 | ```
1615 |
1616 | #### 2.20.1. C# Exception Types
1617 |
1618 | - C# provides a structured solution to the exception handling in the form of try and catch blocks. If an exception occurs in the protected code, the exception is thrown to the first catch block in the call stack. If the exception matches the type specified in the catch block, it will be caught there.
1619 | - The following table lists some of the exception types −
1620 | | Exception | Description |
1621 | | --- | --- |
1622 | | System.Exception | The base class for all exceptions. |
1623 | | System.ApplicationException | The exception that is thrown when a non-fatal application error occurs. |
1624 | | System.IndexOutOfRangeException | The exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds. |
1625 | | System.NullReferenceException | The exception that is thrown when there is an attempt to dereference a null object reference. |
1626 | | System.DivideByZeroException | The exception that is thrown when there is an attempt to divide an integral or decimal value by zero. |
1627 | | System.InvalidCastException | The exception that is thrown for invalid casting or explicit conversion. |
1628 | | System.OutOfMemoryException | The exception that is thrown when there is not enough memory to continue the execution of a program. |
1629 | | System.StackOverflowException | The exception that is thrown when the execution stack overflows because it contains too many nested method calls. |
1630 |
1631 | #### 2.20.2. C# Exception Properties
1632 |
1633 | - The following table lists some of the properties of the exception object −
1634 | | Property | Description |
1635 | | --- | --- |
1636 | | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. |
1637 | | HelpLink | Gets or sets a link to the help file associated with this exception. |
1638 | | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. |
1639 | | InnerException | Gets the Exception instance that caused the current exception. |
1640 | | Message | Gets a message that describes the current exception. |
1641 | | Source | Gets or sets the name of the application or the object that causes the error. |
1642 | | StackTrace | Gets a string representation of the immediate frames on the call stack. |
1643 |
1644 | #### 2.20.3. C# Exception Handling Keywords
1645 |
1646 | - The following table lists some of the keywords that are used to handle exceptions in C# −
1647 | | Keyword | Description |
1648 | | --- | --- |
1649 | | try | The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. |
1650 | | catch | The catch block is used to handle the exception. It must be preceded by the try block which means that we can't use a catch block alone. |
1651 | | finally | The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. |
1652 | | throw | The throw statement allows you to create a custom error. |
1653 |
1654 | #### 2.20.4 C# throw Keyword
1655 |
1656 | - The throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exceptions. It is followed by an exception instance. The following example demonstrates how to use throw keyword in a program −
1657 |
1658 | ```csharp
1659 | using System;
1660 |
1661 | namespace CalculatorApplication {
1662 | class DivNumbers {
1663 | int result;
1664 |
1665 | DivNumbers()
1666 | {
1667 | result = 0;
1668 | }
1669 |
1670 | public void division(int num1, int num2)
1671 | {
1672 | if(num2 == 0)
1673 | {
1674 | throw new DivideByZeroException();
1675 | }
1676 | result = num1 / num2;
1677 |
1678 | }
1679 | static void Main(string[] args)
1680 | {
1681 | DivNumbers d = new DivNumbers();
1682 | try
1683 | {
1684 | d.division(25, 0);
1685 | }
1686 | catch (DivideByZeroException e)
1687 | {
1688 | Console.WriteLine("Exception caught: {0}", e);
1689 | }
1690 | finally
1691 | {
1692 | Console.WriteLine("Result: {0}", result);
1693 | }
1694 | Console.ReadKey();
1695 | }
1696 | }
1697 | }
1698 | ```
1699 |
1700 | #### 2.20.5. C# when Keyword in catch Block
1701 | - The when keyword is used to specify a condition. If the condition specified in the when clause is true, the handler is executed. The following example demonstrates how to use when keyword in a program −
1702 |
1703 | ```csharp
1704 | using System;
1705 |
1706 | namespace CalculatorApplication {
1707 | class DivNumbers {
1708 | int result;
1709 |
1710 | DivNumbers()
1711 | {
1712 | result = 0;
1713 | }
1714 |
1715 | public void division(int num1, int num2)
1716 | {
1717 | if(num2 == 0)
1718 | {
1719 | throw new DivideByZeroException();
1720 | }
1721 | result = num1 / num2;
1722 |
1723 | }
1724 | static void Main(string[] args)
1725 | {
1726 | DivNumbers d = new DivNumbers();
1727 | try
1728 | {
1729 | d.division(25, 0);
1730 | }
1731 | catch (DivideByZeroException e) when (e.Message == "Attempted to divide by zero.")
1732 | {
1733 | Console.WriteLine("Exception caught: {0}", e);
1734 | }
1735 | finally
1736 | {
1737 | Console.WriteLine("Result: {0}", result);
1738 | }
1739 | Console.ReadKey();
1740 | }
1741 | }
1742 | }
1743 | ```
1744 |
1745 | #### 2.20.6. C# Multiple catch Blocks
1746 | - A try block can be followed by multiple catch blocks. The first catch block that handles the specific exception is executed. The following example demonstrates how to use multiple catch blocks in a program −
1747 |
1748 | ```csharp
1749 |
1750 | using System;
1751 |
1752 | namespace CalculatorApplication {
1753 | class DivNumbers {
1754 | int result;
1755 |
1756 | DivNumbers()
1757 | {
1758 | result = 0;
1759 | }
1760 |
1761 | public void division(int num1, int num2)
1762 | {
1763 | try
1764 | {
1765 | result = num1 / num2;
1766 | }
1767 | catch (DivideByZeroException e)
1768 | {
1769 | Console.WriteLine("Exception caught: {0}", e);
1770 | }
1771 | catch (IndexOutOfRangeException e)
1772 | {
1773 | Console.WriteLine("Exception caught: {0}", e);
1774 | }
1775 | finally
1776 | {
1777 | Console.WriteLine("Result: {0}", result);
1778 | }
1779 | }
1780 | static void Main(string[] args)
1781 | {
1782 | DivNumbers d = new DivNumbers();
1783 | d.division(25, 0);
1784 | Console.ReadKey();
1785 | }
1786 | }
1787 | }
1788 | ```
1789 |
1790 | ### 2.21 C# using Keyword
1791 |
1792 | - The using keyword is used for including the namespaces in the program. The using statement obtains one or more resources, executes a statement, and then disposes of the resource.
1793 |
1794 | ### 2.22 C# File I/O
1795 |
1796 | - C# provides various classes to perform various operations on files. In this chapter, you will learn how to read from and write into files by using classes like TextWriter, TextReader, FileStream, StreamReader, StreamWriter, and so on.
1797 | - The following example demonstrates how to use file I/O in a program −
1798 |
1799 | ```csharp
1800 | using System;
1801 |
1802 | namespace CalculatorApplication {
1803 | class Program {
1804 | static void Main(string[] args)
1805 | {
1806 | string[] names = new string[] { "Zara Ali", "Nuha Ali" };
1807 |
1808 | using (System.IO.TextWriter file = new System.IO.StreamWriter(@"D:\test.txt"))
1809 | {
1810 | foreach (string name in names)
1811 | {
1812 | file.WriteLine(name);
1813 | }
1814 | }
1815 |
1816 | string[] lines = System.IO.File.ReadAllLines(@"D:\test.txt");
1817 |
1818 | foreach (string line in lines)
1819 | {
1820 | Console.WriteLine(line);
1821 | }
1822 | }
1823 | }
1824 | }
1825 | ```
1826 |
1827 | ## 3. C# Basic Syntax
1828 |
1829 | - C# is a case-sensitive, strongly-typed language. The following table lists the keywords that are reserved by C#. These reserved keywords may not be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier, but if is not because if is a keyword.
1830 |
1831 | | 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 | int | interface | internal | is | lock | long | namespace | new | null | object | operator | out | 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 | virtual | void | volatile | while |
1832 |
1833 | ### 3.1. C# Identifiers
1834 |
1835 | - A C# identifier is a name used to identify a class, variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (\_) followed by zero or more letters, underscores, and digits (0 to 9).
1836 | - C# does not allow punctuation characters such as @, $, and % within identifiers. C# is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C#.
1837 | - Here are some examples of acceptable identifiers −
1838 |
1839 | ```csharp
1840 | mohd zara abc move_name a_123
1841 | myname50 _temp j a23b9 retVal
1842 | ```
1843 |
1844 | ### 3.2. C# Keywords
1845 |
1846 | - The following list shows the reserved words in C#. These reserved words may not be used as constant or variable or any other identifier names.
1847 |
1848 | ```csharp
1849 | abstract as base bool break byte
1850 | case catch char checked class const
1851 | continue decimal default delegate do double
1852 | else enum event explicit extern false
1853 | finally fixed float for foreach goto
1854 | if implicit in int interface internal
1855 | is lock long namespace new null
1856 | object operator out override params private
1857 | protected public readonly ref return sbyte
1858 | sealed short sizeof stackalloc static string
1859 | struct switch this throw true try
1860 | typeof uint ulong unchecked unsafe ushort
1861 | using virtual void volatile while
1862 | ```
1863 |
1864 | ### 3.3. C# Literals
1865 |
1866 | - A literal is a source code representation of a fixed value. They are represented directly in the code without any computation.
1867 | - Literals can be assigned to any numeric type. Some literals have suffixes that specify the type of the literal. The following table shows examples of literals −
1868 | | Literal | Type | Example |
1869 | | --- | --- | --- |
1870 | | Integer | int | 0, 117, -345, 12345 |
1871 | | Floating-point | double | 0.0, -117.76, 14.56e12 |
1872 | | Boolean | bool | true, false |
1873 | | Character | char | 'A', '\x0041', '\u0041' |
1874 | | String | string | "Hello, World!" |
1875 | | Object | object | null |
1876 |
1877 | ### 3.4. C# Comments
1878 |
1879 | - Comments are used to include additional information about the code, such as a description of the method, its purpose etc. It is also used to prevent the execution of certain lines of code.
1880 | - C# supports single-line and multi-line comments. All characters available inside any comment are ignored by C# compiler.
1881 | - The following example shows how to use comments in C# −
1882 |
1883 | ```csharp
1884 | using System;
1885 |
1886 | namespace HelloWorldApplication {
1887 | class HelloWorld {
1888 | static void Main(string[] args) {
1889 | /* my first program in C# */
1890 | Console.WriteLine("Hello World");
1891 | Console.ReadKey();
1892 | }
1893 | }
1894 | }
1895 | ```
1896 |
1897 | ## 4. C# Classes and Objects
1898 |
1899 | - C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class.
1900 | - The process of creating an object from a class is called instantiation. You can create as many objects as you need of a particular class. An object is also called an instance of a class and the process of creating this object is called instantiation.
1901 |
1902 | ### 4.1. C# Classes
1903 |
1904 | - A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.
1905 |
1906 | #### 4.1.1. Declaring Classes
1907 |
1908 | - Classes are declared by using the class keyword followed by a unique identifier, as shown in the following example −
1909 |
1910 | ```csharp
1911 | class ClassName {
1912 | // class members
1913 | }
1914 | ```
1915 |
1916 | #### 4.1.2. Class Members
1917 |
1918 | - A class can contain any of the following members −
1919 | - Fields
1920 | - Constructors
1921 | - Destructors
1922 | - Constants
1923 | - Properties
1924 | - Indexers
1925 | - Methods
1926 | - Operators
1927 | - Events
1928 | - Nested Types
1929 |
1930 | #### 4.1.3. Creating Objects
1931 |
1932 | - When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.
1933 | - An object is also called an instance of a class and the process of creating this object is called instantiation.
1934 | - When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.
1935 | - The following example demonstrates how to create an object of class Employee −
1936 |
1937 | ```csharp
1938 | Employee Object1 = new Employee();
1939 | ```
1940 |
1941 | #### 4.1.4. new Keyword
1942 |
1943 | - The new keyword is used to create an object of a class. When you create an object, you are creating an instance of a class, therefore "instantiating" a class.
1944 | - The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. This reference is then stored in the variable.
1945 | - The following statements are equivalent −
1946 |
1947 | ```csharp
1948 | Object1 = new Employee();
1949 | Object2 = new Employee();
1950 | ```
1951 |
1952 | #### 4.1.5. Accessing Attributes
1953 |
1954 | - You can access the attributes of an object by using the dot operator (.). The dot operator is also used to access members of a namespace.
1955 | - The following example demonstrates how to access attributes of an object −
1956 |
1957 | ```csharp
1958 | Object1.name = "Zara";
1959 | Object1.salary = 50000;
1960 | ```
1961 |
1962 | #### 4.1.6. Accessing Methods
1963 |
1964 | - You can access the methods of an object by using the dot operator (.). The following example demonstrates how to access methods of an object −
1965 |
1966 | ```csharp
1967 | Object1.SetAge(25);
1968 | Object1.GetAge();
1969 | ```
1970 |
1971 | ### 4.2. C# Objects
1972 |
1973 | - An object is a real-world entity having attributes (data type) and behaviors (functionality). For example, a chair, pen, table, keyboard, bike, etc. are all objects.
1974 | - An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
1975 | - An object has three characteristics −
1976 | - State: represents the data (value) of an object.
1977 | - Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
1978 | - Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user.
1979 |
1980 | #### 4.2.1. State
1981 |
1982 | - The state of an object is represented by its attributes. An attribute is a type of variable that is declared inside a class. Attributes sometimes are called fields, member variables, or instance variables.
1983 | - A class can have many attributes that define its state. The value of an object's attributes defines the state of an object.
1984 |
1985 | #### 4.2.2. C# Auto Properties
1986 |
1987 | - Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
1988 | - The following example demonstrates how to use auto properties in a program −
1989 |
1990 | ```csharp
1991 | using System;
1992 |
1993 | namespace CalculatorApplication {
1994 | class StringManipulator {
1995 | public string MyString { get; set; }
1996 | }
1997 | }
1998 | ```
1999 |
2000 | ##### 4.2.2.1. C# init Accessor
2001 |
2002 | - The init accessor is similar to the set accessor, except that it can be invoked only when the object is initialized during object construction. The following example demonstrates how to use init accessor in a program −
2003 |
2004 | ```csharp
2005 | using System;
2006 |
2007 | namespace CalculatorApplication {
2008 | class StringManipulator {
2009 | public string MyString { get; init; }
2010 | }
2011 | }
2012 | ```
2013 |
2014 | #### 4.2.3. C# Constructors
2015 |
2016 | - A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type. A constructor is an instance method that usually has the same name as the class, and can be used to set the values of the members of an object, either to default or to user-defined values.
2017 | - The following example demonstrates how to use constructors in a program −
2018 |
2019 | ```csharp
2020 | using System;
2021 |
2022 | namespace CalculatorApplication {
2023 | class NumberManipulator {
2024 | public NumberManipulator()
2025 | {
2026 | Console.WriteLine("Constructor is called");
2027 | }
2028 | }
2029 | }
2030 | ```
2031 |
2032 | ##### 4.2.3.1. C# Parameterized Constructors
2033 |
2034 | - A constructor that accepts arguments is known as a parameterized constructor. The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.
2035 | - The following example demonstrates how to use parameterized constructors in a program −
2036 |
2037 | ```csharp
2038 | using System;
2039 |
2040 | namespace CalculatorApplication {
2041 | class NumberManipulator {
2042 | private int val;
2043 | public string MyString {get; set;}
2044 | public NumberManipulator(int val, string str)
2045 | {
2046 | this.val = val;
2047 | MyString = str;
2048 | Console.WriteLine("Constructor is called");
2049 | }
2050 | }
2051 | }
2052 | ```
2053 |
2054 | ##### 4.2.3.2. C# Constructors Overload
2055 |
2056 | - Constructor overloading is a technique in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
2057 | - The following example demonstrates how to use constructor overloading in a program −
2058 |
2059 | ```csharp
2060 | using System;
2061 |
2062 | namespace CalculatorApplication {
2063 | class NumberManipulator {
2064 | private int val;
2065 | public string MyString {get; set;}
2066 | public NumberManipulator()
2067 | {
2068 | val = 100;
2069 | MyString = "Constructor with no parameters";
2070 | }
2071 | public NumberManipulator(int val, string str)
2072 | {
2073 | this.val = val;
2074 | MyString = str;
2075 | Console.WriteLine("Constructor with parameters");
2076 | }
2077 | }
2078 | }
2079 | ```
2080 |
2081 | #### 4.2.4. C# Static Constructors
2082 |
2083 | - Static constructors are used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
2084 | - The following example demonstrates how to use static constructors in a program −
2085 |
2086 | ```csharp
2087 | using System;
2088 |
2089 | namespace CalculatorApplication {
2090 | class NumberManipulator {
2091 | private static int val;
2092 | public string MyString {get; set;}
2093 | static NumberManipulator()
2094 | {
2095 | val = 100;
2096 | Console.WriteLine("Static Constructor is called");
2097 | }
2098 | }
2099 | }
2100 | ```
2101 |
2102 | #### 4.2.5. C# Copy Constructors
2103 |
2104 | - A copy constructor is a special constructor that initializes a new object from an existing object. In C#, a copy constructor is a parameterized constructor and we pass an object of the same class as a parameter.
2105 | - The following example demonstrates how to use copy constructors in a program −
2106 |
2107 | ```csharp
2108 | using System;
2109 |
2110 | namespace CalculatorApplication {
2111 | class NumberManipulator {
2112 | private int val;
2113 | public string MyString {get; set;}
2114 | public NumberManipulator(NumberManipulator n)
2115 | {
2116 | val = n.val;
2117 | MyString = n.MyString;
2118 | Console.WriteLine("Copy Constructor is called");
2119 | }
2120 | }
2121 | }
2122 | ```
2123 |
2124 | #### 4.2.6. C# Destructor Finalizers
2125 |
2126 | - Finalizers are used to perform any necessary final clean-up when a class instance is being collected by the garbage collector.
2127 | - The following example demonstrates how to use destructor finalizers in a program −
2128 |
2129 | ```csharp
2130 | using System;
2131 |
2132 | namespace CalculatorApplication {
2133 | class NumberManipulator {
2134 | private int val;
2135 | public string MyString {get; set;}
2136 | ~NumberManipulator()
2137 | {
2138 | Console.WriteLine("Destructor is called");
2139 | }
2140 | }
2141 | }
2142 | ```
2143 |
2144 | ### 4.3. C# and Object Oriented Programming
2145 |
2146 | - Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).
2147 | - A feature of objects is that an object's own procedures can access and often modify the data fields of itself (objects have a notion of this or self). In OOP, computer programs are designed by making them out of objects that interact with one another. OOP languages are diverse, but the most popular ones are class-based, meaning that objects are instances of classes, which also determine their types.
2148 |
2149 | - The following table lists the main principals of object-oriented programming −
2150 |
2151 | | Principal | Description |
2152 | | --- | --- |
2153 | | Class | A class is a blueprint for the object. We can think of class as an sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object. As many houses can be made from a house's blueprint, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation. |
2154 | | Object | An object (instance) is an instantiation of a class. When class is defined, only the description for the object is defined. Therefore, no memory or storage is allocated. The example for the house is like a class. You have an idea about the type of the house, its construction, and the layout, but you don't know the actual address of the house. |
2155 | | Inheritance | When a class inherits from another class, it takes all the fields and methods from it. Inheritance provides reusability of code. |
2156 | | Polymorphism | Polymorphism is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. There are two types of polymorphism: compile time polymorphism and runtime polymorphism. |
2157 | | Abstraction | Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter). |
2158 | | Encapsulation | Encapsulation is the mechanism of hiding of data implementation by restricting access to public methods. Instance variables are kept private and accessor methods are made public to achieve this. |
2159 |
2160 |
2161 | #### 4.3.1. C# Inheritance
2162 |
2163 | - Inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class.
2164 |
2165 | - In C#, the class which inherits the members of another class is called derived class and the class whose members are inherited is called base class. The derived class is the specialized class for the base class.
2166 |
2167 | - The following example demonstrates how to use inheritance in a program −
2168 |
2169 | ```csharp
2170 | using System;
2171 |
2172 | // Base class
2173 | class Animal {
2174 | public void Eat() {
2175 | Console.WriteLine("The animal is eating.");
2176 | }
2177 | }
2178 |
2179 | // Derived class
2180 | class Dog : Animal {
2181 | public void Bark() {
2182 | Console.WriteLine("The dog is barking.");
2183 | }
2184 | }
2185 |
2186 | class Program {
2187 | static void Main(string[] args) {
2188 | Dog dog = new Dog();
2189 |
2190 | dog.Eat(); // Output: The animal is eating.
2191 | dog.Bark(); // Output: The dog is barking.
2192 |
2193 | Console.ReadKey();
2194 | }
2195 | }
2196 | ```
2197 |
2198 | #### 4.3.2. C# Polimorphism
2199 |
2200 | - Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
2201 |
2202 | - Any C# object that can pass more than one IS-A test is considered to be polymorphic. In C#, there are two ways to implement polymorphism. They are −
2203 |
2204 | - Method overriding
2205 | - Method overloading
2206 |
2207 | - The following example demonstrates how to use polymorphism in a program −
2208 |
2209 | ```csharp
2210 | using System;
2211 |
2212 | // Base class
2213 | class Animal {
2214 | public virtual void MakeSound() {
2215 | Console.WriteLine("The animal makes a sound.");
2216 | }
2217 | }
2218 |
2219 | // Derived class
2220 | class Dog : Animal {
2221 | public override void MakeSound() {
2222 | Console.WriteLine("The dog barks.");
2223 | }
2224 | }
2225 |
2226 | // Derived class
2227 | class Cat : Animal {
2228 | public override void MakeSound() {
2229 | Console.WriteLine("The cat meows.");
2230 | }
2231 | }
2232 |
2233 | class Program {
2234 | static void Main(string[] args) {
2235 | Animal animal = new Animal();
2236 | Animal dog = new Dog();
2237 | Animal cat = new Cat();
2238 |
2239 | animal.MakeSound(); // Output: The animal makes a sound.
2240 | dog.MakeSound(); // Output: The dog barks.
2241 | cat.MakeSound(); // Output: The cat meows.
2242 |
2243 | Console.ReadKey();
2244 | }
2245 | }
2246 |
2247 | ```
2248 |
2249 | #### 4.3.3. C# Abstraction
2250 |
2251 | - Abstraction is one of the key concepts of object-oriented programming (OOP) languages. Its main goal is to handle complexity by hiding unnecessary details from the user.
2252 | - The following example demonstrates how to use abstraction in a program −
2253 |
2254 | ```csharp
2255 | using System;
2256 |
2257 | // Abstract class
2258 | abstract class Animal {
2259 | public abstract void MakeSound();
2260 | }
2261 |
2262 | // Derived class
2263 | class Dog : Animal {
2264 | public override void MakeSound() {
2265 | Console.WriteLine("The dog barks.");
2266 | }
2267 | }
2268 |
2269 | // Derived class
2270 | class Cat : Animal {
2271 | public override void MakeSound() {
2272 | Console.WriteLine("The cat meows.");
2273 | }
2274 | }
2275 |
2276 | class Program {
2277 | static void Main(string[] args) {
2278 | Animal dog = new Dog();
2279 | Animal cat = new Cat();
2280 |
2281 | dog.MakeSound(); // Output: The dog barks.
2282 | cat.MakeSound(); // Output: The cat meows.
2283 |
2284 | Console.ReadKey();
2285 | }
2286 | }
2287 | ```
2288 |
2289 | #### 4.2.4. C# Interfaces
2290 |
2291 | - An interface is a reference type in C#. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
2292 | - An interface is like a contract. Any class that inherits the interface must implement all the members of the interface.
2293 | - The following example demonstrates how to use interfaces in a program −
2294 |
2295 | ```csharp
2296 | using System;
2297 |
2298 | // Interface
2299 | interface IAnimal {
2300 | void MakeSound();
2301 | }
2302 |
2303 | // Class
2304 | class Dog : IAnimal {
2305 | public void MakeSound() {
2306 | Console.WriteLine("The dog barks.");
2307 | }
2308 | }
2309 |
2310 | // Class
2311 | class Cat : IAnimal {
2312 | public void MakeSound() {
2313 | Console.WriteLine("The cat meows.");
2314 | }
2315 | }
2316 |
2317 | class Program {
2318 | static void Main(string[] args) {
2319 | IAnimal dog = new Dog();
2320 | IAnimal cat = new Cat();
2321 |
2322 | dog.MakeSound(); // Output: The dog barks.
2323 | cat.MakeSound(); // Output: The cat meows.
2324 |
2325 | Console.ReadKey();
2326 | }
2327 | }
2328 | ```
2329 |
2330 | ##### 4.2.5.1 C# Multiple Interfaces
2331 |
2332 | - A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces. The following example shows how to use multiple interfaces in a program −
2333 |
2334 | ```csharp
2335 | using System;
2336 |
2337 | // Interface
2338 | interface IAnimal {
2339 | void MakeSound();
2340 | }
2341 |
2342 | // Interface
2343 | interface IMovable {
2344 | void Move();
2345 | }
2346 |
2347 | // Class
2348 | class Dog : IAnimal, IMovable {
2349 | public void MakeSound() {
2350 | Console.WriteLine("The dog barks.");
2351 | }
2352 |
2353 | public void Move() {
2354 | Console.WriteLine("The dog runs.");
2355 | }
2356 | }
2357 |
2358 | class Program {
2359 | static void Main(string[] args) {
2360 | Dog dog = new Dog();
2361 |
2362 | dog.MakeSound(); // Output: The dog barks.
2363 | dog.Move(); // Output: The dog runs.
2364 |
2365 | Console.ReadKey();
2366 | }
2367 | }
2368 | ```
2369 |
2370 | ##### 4.2.5.2 C# Interface Properties
2371 |
2372 | - Interfaces can have properties similar to that of classes. The following example shows how to use interface properties in a program −
2373 |
2374 | ```csharp
2375 | using System;
2376 |
2377 | // Interface
2378 | interface IAnimal {
2379 | string Name { get; set; }
2380 | void MakeSound();
2381 | }
2382 |
2383 | // Class
2384 | class Dog : IAnimal {
2385 | public string Name { get; set; }
2386 |
2387 | public void MakeSound() {
2388 | Console.WriteLine("The dog barks.");
2389 | }
2390 | }
2391 |
2392 | class Program {
2393 | static void Main(string[] args) {
2394 | Dog dog = new Dog();
2395 | dog.Name = "Buddy";
2396 |
2397 | Console.WriteLine("The dog's name is " + dog.Name);
2398 | dog.MakeSound(); // Output: The dog barks.
2399 |
2400 | Console.ReadKey();
2401 | }
2402 | }
2403 | ```
2404 |
2405 | ##### 4.2.5.3 C# Difference between Abstract Classes and Interfaces
2406 |
2407 | - Abstract classes and interfaces are two of the most common constructs in object-oriented programming, and both serve to express abstractions in the type system of C#.
2408 | - The following table lists the differences between abstract classes and interfaces −
2409 |
2410 | | Abstract Class | Interface |
2411 | | -------------- | --------- |
2412 | | An abstract class can provide complete, default code and/or just the details that have to be overridden. | An interface cannot provide any code at all,just the signature. |
2413 | | In case of abstract class, a class may inherit several interfaces. | In case of interface, a class may inherit only one interface. |
2414 | | An abstract class can have non-abstract members. | All interface members are abstract by default. |
2415 | | An abstract class can declare and define constructor and destructor. | An interface cannot declare nor define constructors or destructors. |
2416 | | An abstract class can contain fields that are not static and const, and those fields can have access modifiers. | All interface fields are automatically public, static, and const. |
2417 | | An abstract class can contain fields, members, properties, etc. | An interface can contain only properties, methods, events, and indexers. |
2418 |
2419 | - The purpose of using an abstract class or an interface in C# is to achieve abstraction, which is one of the key concepts of object-oriented programming. Abstraction is the process of hiding unnecessary details from the user and providing a simplified view of the system.
2420 |
2421 | An abstract class is a class that cannot be instantiated and is used as a base class for other classes. It can contain both abstract and non-abstract methods, and it provides a default implementation for some methods that can be overridden by its derived classes. Abstract classes are used when we want to provide a base class for a family of related classes.
2422 |
2423 | An interface is a reference type that contains only abstract methods, properties, and events. It defines a contract that a class must implement, regardless of its inheritance hierarchy. A class can implement multiple interfaces, but it cannot inherit from multiple classes. Interfaces are used when we want to define a set of methods that a class must implement, regardless of its inheritance hierarchy.
2424 |
2425 | Both abstract classes and interfaces are used to achieve abstraction, but they have different purposes and usage scenarios. Abstract classes are used when we want to provide a default implementation of some methods, while interfaces are used when we want to define a contract that a class must implement.
2426 |
2427 | #### 4.2.6. C# Encapsulation
2428 |
2429 | - Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of bundling data and methods that work on that data within one unit, e.g., a class in C#.
2430 |
2431 | - This concept is also often used to hide the internal representation, or state, of an object from the outside.
2432 | - The following example demonstrates how to use encapsulation in a program −
2433 |
2434 | ```csharp
2435 | using System;
2436 |
2437 | // Class
2438 | class BankAccount {
2439 | private double balance;
2440 |
2441 | public void Deposit(double amount) {
2442 | balance += amount;
2443 | }
2444 |
2445 | public void Withdraw(double amount) {
2446 | if (balance >= amount) {
2447 | balance -= amount;
2448 | } else {
2449 | Console.WriteLine("Insufficient funds.");
2450 | }
2451 | }
2452 |
2453 | public double GetBalance() {
2454 | return balance;
2455 | }
2456 | }
2457 |
2458 | class Program {
2459 | static void Main(string[] args) {
2460 | BankAccount account = new BankAccount();
2461 |
2462 | account.Deposit(1000);
2463 | Console.WriteLine("Balance: " + account.GetBalance()); // Output: Balance: 1000
2464 |
2465 | account.Withdraw(500);
2466 | Console.WriteLine("Balance: " + account.GetBalance()); // Output: Balance: 500
2467 |
2468 | account.Withdraw(1000);
2469 | Console.WriteLine("Balance: " + account.GetBalance()); // Output: Insufficient funds. Balance: 500
2470 |
2471 | Console.ReadKey();
2472 | }
2473 | }
2474 | ```
2475 | #### 4.2.7. C# Class Methods
2476 |
2477 | - A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method.
2478 |
2479 | ##### 4.2.7.1. Abstract Methods
2480 |
2481 | - An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this −
2482 |
2483 | ```csharp
2484 | using System;
2485 |
2486 | // Abstract class
2487 | abstract class Shape {
2488 | public abstract double GetArea();
2489 | }
2490 |
2491 | // Derived class
2492 | class Rectangle : Shape {
2493 | private double length;
2494 | private double width;
2495 |
2496 | public Rectangle(double l, double w) {
2497 | length = l;
2498 | width = w;
2499 | }
2500 |
2501 | public override double GetArea() {
2502 | return length * width;
2503 | }
2504 | }
2505 |
2506 | class Program {
2507 | static void Main(string[] args) {
2508 | Rectangle rect = new Rectangle(5, 10);
2509 |
2510 | Console.WriteLine("Area of rectangle: " + rect.GetArea()); // Output: Area of rectangle: 50
2511 |
2512 | Console.ReadKey();
2513 | }
2514 | }
2515 | ```
2516 |
2517 | ##### 4.2.7.2. Virtual Methods
2518 |
2519 | - A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived classes. It is used to provide the specific implementation of the method.
2520 |
2521 | - The following example demonstrates how to use virtual methods in a program −
2522 |
2523 | ```csharp
2524 | using System;
2525 |
2526 | // Base class
2527 | class Shape {
2528 | public virtual double GetArea() {
2529 | return 0;
2530 | }
2531 | }
2532 |
2533 | // Derived class
2534 | class Rectangle : Shape {
2535 | private double length;
2536 | private double width;
2537 |
2538 | public Rectangle(double l, double w) {
2539 | length = l;
2540 | width = w;
2541 | }
2542 |
2543 | public override double GetArea() {
2544 | return length * width;
2545 | }
2546 | }
2547 |
2548 | class Program {
2549 | static void Main(string[] args) {
2550 | Shape shape = new Shape();
2551 | Rectangle rect = new Rectangle(5, 10);
2552 |
2553 | Console.WriteLine("Area of shape: " + shape.GetArea()); // Output: Area of shape: 0
2554 | Console.WriteLine("Area of rectangle: " + rect.GetArea()); // Output: Area of rectangle: 50
2555 |
2556 | Console.ReadKey();
2557 | }
2558 | }
2559 | ```
2560 |
2561 | ##### 4.2.7.3. override Keyword
2562 |
2563 | - The override keyword is used to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
2564 | - The following example demonstrates how to use the override keyword in a program −
2565 |
2566 | ```csharp
2567 | using System;
2568 |
2569 | // Base class
2570 | class Shape {
2571 | public virtual double GetArea() {
2572 | return 0;
2573 | }
2574 | }
2575 |
2576 | // Derived class
2577 | class Rectangle : Shape {
2578 | private double length;
2579 | private double width;
2580 |
2581 | public Rectangle(double l, double w) {
2582 | length = l;
2583 | width = w;
2584 | }
2585 |
2586 | public override double GetArea() {
2587 | return length * width;
2588 | }
2589 | }
2590 |
2591 | // Derived class
2592 | class Square : Rectangle {
2593 | public Square(double side) : base(side, side) {
2594 | }
2595 | }
2596 |
2597 | class Program {
2598 | static void Main(string[] args) {
2599 | Shape shape = new Shape();
2600 | Rectangle rect = new Rectangle(5, 10);
2601 | Square square = new Square(5);
2602 |
2603 | Console.WriteLine("Area of shape: " + shape.GetArea()); // Output: Area of shape: 0
2604 | Console.WriteLine("Area of rectangle: " + rect.GetArea()); // Output: Area of rectangle: 50
2605 | Console.WriteLine("Area of square: " + square.GetArea()); // Output: Area of square: 25
2606 |
2607 | Console.ReadKey();
2608 | }
2609 | }
2610 | ```
2611 | ## 5. Programming Principles
2612 |
2613 | ### 5.1. SOLID
2614 |
2615 | *To Be Cont.*
2616 |
2617 | Prepared with the help of CoPilot
2618 |
--------------------------------------------------------------------------------