Basics of C#

 

1. Variables and Data Types:

  • Variables: In C#, variables are used to store data temporarily. They must be declared with a data type before use.
    int age; // Declaration age = 25; // Assignment
  • Data Types: C# supports various data types such as integers (int, long), floating-point numbers (float, double), characters (char), strings (string), booleans (bool), etc.
    int number = 10; double pi = 3.14; char grade = 'A'; string message = "Hello, World!"; bool isTrue = true;

2. Operators:

  • Arithmetic Operators: Used for basic arithmetic operations such as addition, subtraction, multiplication, division, and modulus.
  • Relational Operators: Used to compare two values and return a boolean result (true or false).
  • Logical Operators: Used to perform logical operations such as AND (&&), OR (||), and NOT (!).
  • Assignment Operators: Used to assign values to variables (=, +=, -=).
  • Increment and Decrement Operators: Used to increment (++) or decrement (--) the value of a variable.
  • Conditional Operator (Ternary): Used for conditional expressions (condition ? true_expression : false_expression).

3. Control Structures:

  • if-else Statements: Used for conditional branching based on a condition.
    if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false }
  • switch Statements: Used for multi-way branching based on the value of an expression.
    switch (expression) { case value1: // Code to execute if expression equals value1 break; case value2: // Code to execute if expression equals value2 break; default: // Code to execute if expression doesn't match any case break; }
  • Loops: Used for repetitive execution of code.
    • for Loop
    • while Loop
    • do-while Loop
    for (int i = 0; i < 5; i++) { // Code to execute repeatedly }

4. Methods:

  • Definition: Methods are blocks of code that perform a specific task. They can accept input parameters and return a value.
    int Add(int x, int y) { return x + y; }
  • Calling Methods: Methods are called by their name, followed by parentheses containing any arguments.
    int result = Add(5, 3);

5. Comments:

  • Single-Line Comments: Used to add comments on a single line using //.
  • Multi-Line Comments: Used to add comments spanning multiple lines using /* */.
    // This is a single-line comment /* This is a multi-line comment spanning multiple lines */

6. Arrays:

  • Definition: Arrays are used to store multiple values of the same data type in a single variable.
    int[] numbers = new int[5]; // Declaration and initialization numbers[0] = 10; numbers[1] = 20;
  • Accessing Elements: Elements of an array are accessed using index notation ([index]).
    int thirdNumber = numbers[2]; // Accessing the third element

7. Strings:

  • Definition: Strings are used to represent text data in C#.
    string name = "John";
  • String Concatenation: Strings can be concatenated using the + operator or string interpolation ($"{variable}").
    string greeting = "Hello, " + name + "!"; string message = $"Welcome, {name}!";
  • String Methods: C# provides various methods for manipulating strings, such as Length, ToUpper(), ToLower(), Substring(), IndexOf(), Split(), etc.

8. Classes and Objects:

  • Classes: Classes are blueprints for creating objects. They encapsulate data and behavior.
    public class Person { public string Name { get; set; } public int Age { get; set; } }
  • Objects: Objects are instances of classes. They are created using the new keyword.
    Person person = new Person(); person.Name = "Alice"; person.Age = 30;

9. Constructors:

  • Definition: Constructors are special methods used to initialize objects when they are created.
    public class Person { public Person(string name, int age) { Name = name; Age = age; } }
  • Default Constructor: If no constructor is defined, a default parameterless constructor is provided by the compiler.

10. Access Modifiers:

  • Public: Accessible from any code in the same assembly or another assembly.
  • Private: Accessible only within the same class.
  • Protected: Accessible within the same class or derived classes.
  • Internal: Accessible within the same assembly.
  • Protected Internal: Accessible within the same assembly or derived classes outside the assembly.

11. Static Members:

  • Static Fields and Methods: Static members belong to the class itself rather than instances of the class.
    public class MathHelper { public static int Add(int x, int y) { return x + y; } }
  • Accessing Static Members: Static members are accessed using the class name (ClassName.MemberName).
    int sum = MathHelper.Add(5, 3);

12. Enums:

  • Definition: Enums (enumerations) are used to define a set of named constants.
    public enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
  • Usage: Enums provide a way to represent a fixed set of values and are often used to improve code readability and maintainability.

13. Nullable Types:

  • Definition: Nullable types allow variables to hold null values in addition to their normal range of values.
    int? nullableInt = null;
  • Syntax: Nullable types are declared by appending ? to the underlying value type (int?, double?, bool?, etc.).
  • Nullable Value Access: Use the Value property or the null coalescing operator (??) to access the underlying value of a nullable type.

14. Arrays and Collections:

  • Arrays: Apart from traditional arrays, C# provides specialized array-like collections such as List<T>, Dictionary<TKey, TValue>, HashSet<T>, etc.
  • List<T> Example:
    List<int> numbers = new List<int>(); numbers.Add(10); numbers.Add(20);

15. Exception Handling:

  • try-catch Blocks: Used to handle exceptions and gracefully recover from errors.
    try { // Code that may throw an exception } catch (Exception ex) { // Code to handle the exception }
  • throw Statement: Used to raise custom exceptions or rethrow caught exceptions.

16. LINQ (Language Integrated Query):

  • Definition: LINQ provides a unified way to query data from different data sources using a common syntax.
  • LINQ Query Syntax:
    var query = from number in numbers where number > 10 select number;
  • LINQ Method Syntax:
    var query = numbers.Where(number => number > 10);

17. File I/O:

  • Reading from Files: Use classes from the System.IO namespace such as StreamReader or File.ReadAllText() to read from text files.
  • Writing to Files: Use classes like StreamWriter or File.WriteAllText() to write data to text files.

18. Delegates and Events:

  • Delegates: Delegates are used to define and pass references to methods as parameters. They enable callback mechanisms and event handling.
  • Events: Events are a special type of delegate that encapsulate the mechanism for notifying subscribers when something happens.

19. Attributes:

  • Definition: Attributes provide a way to add metadata to types and members in C# code.
  • Usage: Attributes are commonly used for compiler directives, reflection, serialization, and other metadata-driven scenarios.
  • Examples: [Serializable], [Obsolete], [Conditional], etc.

20. Asynchronous Programming:

  • Async and Await: Asynchronous programming enables non-blocking execution of code. Use the async and await keywords to work with asynchronous methods.
  • Task-based Asynchronous Pattern (TAP): Asynchronous methods return a Task or Task<T> object, representing an ongoing asynchronous operation.

Understanding these fundamental concepts will give you a solid foundation in C# programming and prepare you for more advanced topics. Experiment with these concepts in your code and explore additional resources for further learning.

Post a Comment

0 Comments