Skip to content

Latest commit

 

History

History
63 lines (50 loc) · 2.88 KB

File metadata and controls

63 lines (50 loc) · 2.88 KB

Let's dive into the fundamentals of C# syntax and basic constructs. C# is a versatile, object-oriented programming language developed by Microsoft, part of the .NET framework. Understanding its syntax and constructs is crucial for building applications in C#.

1. C# Program Structure

  • Namespace Declaration: A namespace is a collection of classes. The using System; statement includes the System namespace containing fundamental classes.
  • Class Declaration: A C# program contains classes. A class encapsulates data for the object.
  • Main Method: Every C# program must have a Main method, where program execution begins.
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

2. Data Types and Variables

  • Data Types: Common types include int (integer), double (double-precision floating-point), char (single character), and string (sequence of characters).
  • Variables: Used to store data. For example, int number = 5; declares an integer variable.

3. Operators

  • Arithmetic Operators: +, -, *, /, % for basic mathematical operations.
  • Relational Operators: ==, !=, <, >, <=, >= for comparing values.
  • Logical Operators: && (AND), || (OR), ! (NOT).

4. Control Structures

  • If-Else Statements: Used for conditional execution of code blocks.
  • Loops: for, while, do-while for repeating a block of code.
  • Switch Statements: For selecting one of many code blocks to be executed.

5. Methods

  • Defined to perform specific tasks. Methods can return a value or be void.
  • Can take parameters.
public int AddNumbers(int num1, int num2)
{
    return num1 + num2;
}

6. Arrays

  • Collections of variables of the same type.
  • Declared with a type, followed by square brackets. For example, int[] numbers;.

7. Exception Handling

  • Uses try, catch, and finally blocks to handle errors.
  • try contains the code that may throw an exception, catch handles the exception, and finally executes code regardless of whether an exception occurred.

8. Comments

  • Single-line comments: // This is a comment
  • Multi-line comments: /* This is a multi-line comment */

9. Namespaces

  • Provide a way to organize your code and control the scope of class and method names.

Understanding these basic constructs is crucial as they form the foundation of more complex programming tasks in C#. Practice and application of these concepts in small projects will greatly enhance your understanding and proficiency in C#. If you need more in-depth explanations or practical examples on any of these topics, feel free to ask!