Welcome to the exciting world of C# programming! Whether you’re taking your first steps in coding or leveling up your skills, understanding the basics of C# is crucial. In this guide, we’ll explore the core concepts of C# – syntax, variables, and data types – with explanations and examples to make the learning process enjoyable.
Category | Syntax/Example | Description |
---|---|---|
Hello World | Console.WriteLine("Hello, World!"); | Outputs the text “Hello, World!” to the console. |
Variables | int myNumber = 42; | Declares an integer variable named myNumber and assigns the value 42. |
Comments | // This is a single-line comment | Single-line comment starts with // . |
/* This is a multi-line comment */ | Multi-line comment starts with /* and ends with */ . | |
Data Types | byte myByte = 255; | 8-bit unsigned integer. |
sbyte mySByte = -128; | 8-bit signed integer. | |
short myShort = 32767; | 16-bit signed integer. | |
ushort myUShort = 65535; | 16-bit unsigned integer. | |
int myInt = 42; | 32-bit signed integer. | |
uint myUInt = 4294967295U; | 32-bit unsigned integer. | |
long myLong = 9223372036854775807L; | 64-bit signed integer. | |
ulong myULong = 18446744073709551615UL; | 64-bit unsigned integer. | |
float myFloat = 3.14f; | 32-bit single-precision floating-point. | |
double myDouble = 3.14; | 64-bit double-precision floating-point. | |
decimal myDecimal = 123.45m; | 128-bit decimal type for financial calculations. | |
char myChar = 'A'; | 16-bit Unicode character. | |
bool isTrue = true; | Boolean (true/false) value. | |
Arithmetic Operators | int result = 10 + 5; | Addition. |
int result = 10 - 5; | Subtraction. | |
int result = 10 * 5; | Multiplication. | |
int result = 10 / 5; | Division. | |
int result = 10 % 3; | Modulus (remainder of division). | |
Comparison Operators | bool isEqual = (a == b); | Equality. |
bool isNotEqual = (a != b); | Inequality. | |
bool greaterThan = (a > b); | Greater than. | |
bool lessThan = (a < b); | Less than. | |
bool greaterOrEqual = (a >= b); | Greater than or equal to. | |
bool lessOrEqual = (a <= b); | Less than or equal to. | |
Logical Operators | bool result = (x && y); | Logical AND. |
`bool result = (x | ||
bool result = !x; | Logical NOT. | |
Conditional Statements | csharp if (condition) { /* code block */ } | Executes code if the condition is true. |
csharp else { /* code block */ } | Executes code if the preceding condition is false. | |
csharp switch (variable) { case value: /* code */ break; default: /* code */ } | Executes code based on the value of the variable. | |
Loops | csharp for (int i = 0; i < 5; i++) { /* code block */ } | Executes code repeatedly for a specified number of iterations. |
csharp while (condition) { /* code block */ } | Executes code while a condition is true. | |
csharp do { /* code block */ } while (condition); | Executes code at least once and then repeats while a condition is true. | |
Arrays | int[] myArray = { 1, 2, 3, 4, 5 }; | Declares and initializes an integer array. |
int element = myArray[2]; | Accesses an element in the array by index. | |
Functions/Methods | csharp void MyMethod() { /* code block */ } | Declares a void method named MyMethod . |
csharp int Add(int a, int b) { return a + b; } | Declares a method that returns an integer. | |
int result = Add(10, 5); | Calls the Add method with arguments. | |
Classes | csharp class MyClass { /* Class members */ } | Declares a class named MyClass . |
Objects | csharp MyClass obj = new MyClass(); | Creates an instance of the MyClass class. |
Properties | csharp public int MyProperty { get; set; } | Declares an auto-implemented property. |
Constructors | csharp public MyClass(int value) { /* Constructor logic */ } | Defines a constructor for MyClass . |
Inheritance | csharp class DerivedClass : BaseClass { /* Derived class members */ } | Declares a class that inherits from another class. |
Interfaces | csharp interface IDrawable { void Draw(); } | Declares an interface with a method. |
Delegates | csharp delegate int MathOperation(int x, int y); | Declares a delegate for a math operation. |
Events | csharp public event EventHandler MyEvent; | Declares an event named MyEvent . |
Exception Handling | csharp try { /* Code that may throw an exception */ } catch (Exception ex) { /* Handle exception */ } finally { /* Code to execute regardless of whether an exception was thrown */ } | Handles exceptions using try, catch, and finally blocks. |
Nullable Types | int? nullableInt = null; | Represents a nullable value type. |
C# Syntax
Table of Contents
Statements and Expressions
In C# programming, statements are like sentences, and expressions are the building blocks within those sentences. A statement is a complete instruction, and an expression is a smaller part of that instruction.
Example:
// Statement example
int age = 25;
// Expression example
int newAge = age + 5;
Here, the statement declares a variable “age” and assigns it the value 25. The expression then takes that age, adds 5, and assigns the result to a new variable named “newAge.”
Variables and Identifiers
Variables act as containers to store information in a C# program. An identifier is the name given to a variable, providing a way to reference and use it in your code.
Example:
// Variable declaration
string name = "John";
In this example, we declare a variable named “name” and assign it the value “John.” The variable “name” can now be used to store and retrieve the name “John” throughout the program.
Control Flow Statements
Control flow statements direct the flow of a program’s execution, making decisions and repeating actions. Key control flow statements include if statements, loops, and switch statements.
Example:
// Control flow with if statement
int score = 80;
if (score >= 70) {
Console.WriteLine("You passed!");
} else {
Console.WriteLine("You need to improve.");
}
This example uses an if statement to check if the score is equal to or greater than 70. If true, it prints “You passed!”; otherwise, it suggests improvement.
Understanding C# Variables
Variable Declaration
Declaring a variable in C# involves specifying its type and giving it a name. Once declared, a variable can be used to store and manipulate data.
Example:
// Variable declaration
int numberOfApples = 10;
Here, we declare a variable named “numberOfApples” with the int type and assign it the value 10. This variable can be used to represent the quantity of apples in the program.
Scope and Lifetime of Variables
The scope of a variable defines where it can be accessed in a program, and the lifetime determines how long it exists. Variables can have local or global scope.
Example:
// Variable with local scope
void MyFunction() {
int localVar = 5;
Console.WriteLine(localVar);
}
The variable “localVar” is declared inside the function, making it accessible only within that function. Once the function ends, the variable’s lifetime concludes.
Constants and Readonly Variables
Constants are values that do not change throughout the program, while readonly variables can only be assigned a value once but remain accessible.
Example:
// Constant example
const double PI = 3.14;
// Readonly variable example
readonly string country = "Canada";
The constant PI will always be 3.14, and the readonly variable “country” can be set once but remains accessible throughout the program.
C# Data Types
Category | Data Types | Description | Example |
---|---|---|---|
Numeric Types | byte | 8-bit unsigned integer | byte myByte = 255; |
sbyte | 8-bit signed integer | sbyte mySByte = -128; | |
short | 16-bit signed integer | short myShort = 32767; | |
ushort | 16-bit unsigned integer | ushort myUShort = 65535; | |
int | 32-bit signed integer (most commonly used) | int myInt = 42; | |
uint | 32-bit unsigned integer | uint myUInt = 4294967295U; | |
long | 64-bit signed integer | long myLong = 9223372036854775807L; | |
ulong | 64-bit unsigned integer | ulong myULong = 18446744073709551615UL; | |
float | 32-bit single-precision floating-point | float myFloat = 3.14f; | |
double | 64-bit double-precision floating-point | double myDouble = 3.14; | |
decimal | 128-bit decimal type for financial/money | decimal myDecimal = 123.45m; | |
Character Type | char | 16-bit Unicode character | char myChar = 'A'; |
Boolean Type | bool | Represents true or false | bool myBool = true; |
String Type | string | Represents a sequence of characters | string myString = "Hello, C#"; |
Object Type | object | Base type for all C# types | object myObject = new SomeClass(); |
Nullable Types | Various (e.g., int? , float? ) | Allows representing an additional value, null | int? myNullableInt = null; |
Enumerations | enum | Defines a set of named values | csharp enum Days { Sunday, Monday, Tuesday } |
Arrays | Various (e.g., int[] , string[] ) | Represents a collection of elements | int[] myArray = { 1, 2, 3, 4, 5 }; |
Structs | struct | Custom value types | csharp struct Point { public int X; public int Y; } |
Classes | class | Custom reference types | csharp class MyClass { /* Class members */ } |
Interfaces | interface | Defines a contract for classes to implement | csharp interface IDrawable { void Draw(); } |
Delegates | delegate | Declares and encapsulates methods | csharp delegate int MathOperation(int x, int y); |
Primitive Data Types
Primitive data types are the basic building blocks that represent simple values. Common primitive data types in C# include integers, floats, chars, and booleans.
Example:
// Primitive data types
int age = 25; // Integer
float price = 19.99f; // Float
char grade = 'A'; // Char
bool isPassed = true; // Boolean
In this example, we use different primitive data types to store information like age, price, grade, and pass/fail status.
Composite Data Types
Composite data types allow developers to group multiple values into a single variable. Examples include arrays, structures, and enums.
Example:
// Composite data types
int[] numbers = {1, 2, 3, 4}; // Array
struct Point { int x, y; } // Structure
enum Days { Monday, Tuesday, Wednesday } // Enum
Here, an array holds multiple numbers, a structure groups x and y coordinates, and an enum provides names for days of the week.
Strings and Objects: C# Essentials
Strings are sequences of characters, and objects are instances of user-defined classes. Understanding these concepts helps organize and manage information effectively.
Example:
// String and Object
string greeting = "Hello, ";
string name = "John";
string welcomeMessage = greeting + name; // Concatenating strings
class Car {
public string model;
public int year;
}
Car myCar = new Car(); // Creating an object
myCar.model = "Toyota";
myCar.year = 2022;
In this example, strings are concatenated to form a welcome message, and an object representing a car is created with model and manufacturing year attributes.
Conclusion
Congratulations! You’ve now explored the foundational elements of C# programming with practical examples. Remember, practice is key. Use these explanations and examples as your starting point, and enjoy your coding journey in C#! Happy coding!