C# Basics
C# Basics
1. Structure of a C# Program
A basic C# program has the following structure:
Explanation:
using System;→ Includes theSystemnamespace (provides Console class).namespace MyApp→ Groups related classes.class Program→ Defines a class.static void Main(string[] args)→ Main method, program entry point.Console.WriteLine()→ Prints output to the console.
2. Variables & Data Types
Variables store data in memory. Each variable has a data type that defines the kind of data it can hold.
Common Data Types:
| TypeSizeExampleDescription | |||
| int | 4 bytes | int age = 25; | Integer numbers |
| float | 4 bytes | float price = 10.5f; | Single-precision decimal |
| double | 8 bytes | double salary = 45000.75; | Double-precision decimal |
| char | 2 bytes | char grade = 'A'; | Single character |
| string | - | string name = "John"; | Sequence of characters |
| bool | 1 byte | bool isActive = true; | True/False value |
Example:
3. Constants & Readonly
- Constant: Value cannot change after compilation.
- Readonly: Value can be set at runtime but cannot be changed afterward.
4. Keywords in C#
Keywords are reserved words with special meaning in C#. Examples:
5. Comments in C#
- Single-line comment:
// This is a comment - Multi-line comment:
- XML comments: Useful for documentation.
6. Operators in C#
6.1 Arithmetic Operators
6.2 Assignment Operators
6.3 Comparison Operators
6.4 Logical Operators
6.5 Bitwise Operators
Summary of Chapter 2:
- A C# program consists of namespaces, classes, and the Main method.
- Variables store data and have specific data types.
- Constants and readonly fields help protect values.
- Keywords are reserved words with predefined meaning.
- Comments improve code readability.
- Operators perform arithmetic, assignment, comparison, logical, and bitwise operations.