C# Basics
Welcome to the foundational concepts of C#! This guide will walk you through the essential building blocks of the C# programming language, equipping you with the knowledge to start building robust and efficient applications on the .NET platform.
1. Introduction to C#
C# (pronounced "C sharp") is a modern, object-oriented programming language developed by Microsoft. It is designed for building a wide range of applications, from desktop software and web services to mobile apps and games. C# is a type-safe language that promotes robust development and helps developers build scalable and maintainable applications.
Key Features:
- Object-Oriented: Encapsulates data and behavior into objects.
- Type-Safe: Reduces runtime errors by enforcing type checking.
- Component-Oriented: Facilitates building reusable software components.
- Modern: Continuously evolving with new features and improvements.
2. Variables and Data Types
Variables are containers for storing data values. In C#, every variable has a specific data type, which determines the kind of value it can hold and the operations that can be performed on it.
Common Data Types:
int: Stores whole numbers (e.g., 10, -5).double: Stores floating-point numbers (e.g., 3.14, -0.5).bool: Stores a boolean value (trueorfalse).char: Stores a single character (e.g., 'A', '$').string: Stores a sequence of characters (e.g., "Hello, World!").
x, use userAge.
Example:
int age = 30;
double price = 19.99;
bool isActive = true;
char initial = 'J';
string name = "Jane Doe";
3. Operators
Operators are symbols that perform operations on variables and values. C# supports various types of operators:
Arithmetic Operators:
+(Addition)-(Subtraction)*(Multiplication)/(Division)%(Modulo - remainder of division)
Comparison Operators:
==(Equal to)!=(Not equal to)>(Greater than)<(Less than)>=(Greater than or equal to)<=(Less than or equal to)
Logical Operators:
&&(Logical AND)||(Logical OR)!(Logical NOT)
Example:
int a = 10;
int b = 5;
int sum = a + b; // sum is 15
bool isGreater = a > b; // isGreater is true
4. Control Flow
Control flow statements allow you to control the order in which code is executed. This is crucial for making decisions and repeating actions in your programs.
Conditional Statements (if, else if, else):
Used to execute code based on whether a condition is true or false.
if (score > 90) {
Console.WriteLine("Excellent!");
} else if (score > 75) {
Console.WriteLine("Good job!");
} else {
Console.WriteLine("Keep practicing.");
}
Looping Statements (for, while, foreach):
Used to execute a block of code repeatedly.
// for loop
for (int i = 0; i < 5; i++) {
Console.WriteLine("Iteration: " + i);
}
// while loop
int count = 0;
while (count < 3) {
Console.WriteLine("Count: " + count);
count++;
}
// foreach loop (for collections)
string[] fruits = {"Apple", "Banana", "Cherry"};
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
5. Arrays
Arrays are used to store multiple values of the same data type in a single variable. They provide a fixed-size collection of elements.
Declaring and Initializing Arrays:
// Declare an integer array
int[] numbers = new int[5]; // An array of 5 integers
// Initialize with values
int[] scores = { 90, 85, 92, 78, 88 };
// Accessing elements (index starts at 0)
int firstScore = scores[0]; // firstScore is 90
int thirdScore = scores[2]; // thirdScore is 92
Array Length:
int numberOfScores = scores.Length; // numberOfScores is 5
6. Methods
Methods (also known as functions) are blocks of code that perform a specific task. They help in organizing code, making it reusable, and improving readability.
Defining and Calling Methods:
// Method that returns nothing (void) and takes no parameters
void Greet() {
Console.WriteLine("Hello there!");
}
// Method that takes parameters and returns a value
int Add(int num1, int num2) {
return num1 + num2;
}
// Calling the methods
Greet(); // Output: Hello there!
int result = Add(10, 20); // result is 30
Console.WriteLine("The sum is: " + result); // Output: The sum is: 30
7. Classes and Objects
C# is an object-oriented programming (OOP) language. Classes are blueprints for creating objects, which are instances of those classes. Objects have properties (data) and methods (behavior).
Defining a Class:
public class Dog {
// Properties
public string Name;
public string Breed;
// Constructor (special method to initialize objects)
public Dog(string name, string breed) {
Name = name;
Breed = breed;
}
// Method
public void Bark() {
Console.WriteLine(Name + " says Woof!");
}
}
Creating and Using Objects:
// Create an object of the Dog class
Dog myDog = new Dog("Buddy", "Golden Retriever");
// Access properties
Console.WriteLine("My dog's name is: " + myDog.Name); // Output: My dog's name is: Buddy
// Call methods
myDog.Bark(); // Output: Buddy says Woof!
8. Inheritance
Inheritance is a mechanism where one class (derived class) acquires the properties and methods of another class (base class). This promotes code reuse and establishes a hierarchical relationship.
Example:
// Base class
public class Animal {
public string Species;
public void Eat() {
Console.WriteLine("This animal eats.");
}
}
// Derived class
public class Cat : Animal {
public void Meow() {
Console.WriteLine("Meow!");
}
}
// Using inheritance
Cat myCat = new Cat();
myCat.Species = "Feline"; // Inherited from Animal
myCat.Eat(); // Inherited from Animal
myCat.Meow(); // Defined in Cat
9. Interfaces
An interface is a contract that defines a set of method signatures without implementation. A class that implements an interface must provide an implementation for all methods declared in the interface.
Defining and Implementing an Interface:
// Interface definition
public interface IPlayable {
void Play();
}
// Class implementing the interface
public class AudioFile : IPlayable {
public void Play() {
Console.WriteLine("Playing audio...");
}
}
// Using the interface
IPlayable myMusic = new AudioFile();
myMusic.Play(); // Output: Playing audio...
10. Exception Handling
Exceptions are runtime errors that disrupt the normal flow of a program. Exception handling allows you to gracefully manage these errors, preventing your application from crashing.
try-catch Blocks:
The try block contains the code that might throw an exception, and the catch block handles the exception if it occurs.
try {
// Code that might cause an error
int result = 10 / 0; // This will throw a DivideByZeroException
Console.WriteLine(result);
} catch (DivideByZeroException ex) {
// Handle the specific exception
Console.WriteLine("Error: Cannot divide by zero.");
Console.WriteLine("Details: " + ex.Message);
} catch (Exception ex) {
// Handle any other unexpected exceptions
Console.WriteLine("An unexpected error occurred.");
} finally {
// Code in the finally block always executes, whether an exception occurred or not
Console.WriteLine("Exception handling finished.");
}
This concludes our introduction to C# basics. Continue exploring the documentation to delve deeper into more advanced topics!