.NET C# Basics
Introduction
C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft as part of the .NET platform. It was designed to be simple, powerful, type-safe, and internet-centric. Since its first release in 2002, C# has evolved significantly and become one of the most popular programming languages in the world.
C# combines the best features of languages like C++, Java, and Visual Basic, making it both robust and easy to learn. Whether you want to build desktop applications, web services, mobile apps, games, or cloud-based solutions, C# provides the tools and framework to accomplish your goals.
In this tutorial, we'll explore the fundamental concepts of C#, its syntax, and how it integrates with the .NET ecosystem.
Environment Setup
Before diving into C# programming, you need to set up your development environment:
-
Install the .NET SDK: Download and install the latest .NET SDK from Microsoft's official website.
-
Choose an IDE or Text Editor:
- Visual Studio (comprehensive IDE with full C# support)
- Visual Studio Code (lightweight editor with C# extensions)
- JetBrains Rider (cross-platform .NET IDE)
-
Hello World Application: Let's create our first C# program.
# Create a new console application
dotnet new console -n HelloCSharp
cd HelloCSharp
Your First C# Program
After setting up your environment, let's write our first C# program - the classic "Hello World":
using System;
namespace HelloCSharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, C# World!");
}
}
}
Output:
Hello, C# World!
Let's break down this code:
using System;
- This is a directive that includes the System namespace, giving us access to basic classes like Console.namespace HelloCSharp
- Namespaces organize code and prevent name clashes.class Program
- Every C# program needs at least one class.static void Main(string[] args)
- The entry point of every C# console application.Console.WriteLine("Hello, C# World!");
- Prints text to the console.
C# Basic Syntax
Variables and Data Types
C# is a strongly-typed language, which means you need to declare the type of each variable.
// Declaring variables
int number = 10;
double decimalNumber = 10.5;
char character = 'A';
string text = "This is a string";
bool isTrue = true;
// Displaying variables
Console.WriteLine($"Integer: {number}");
Console.WriteLine($"Double: {decimalNumber}");
Console.WriteLine($"Character: {character}");
Console.WriteLine($"String: {text}");
Console.WriteLine($"Boolean: {isTrue}");
Output:
Integer: 10
Double: 10.5
Character: A
String: This is a string
Boolean: True
Constants
Constants are immutable values that cannot be changed during program execution.
const double PI = 3.14159;
Console.WriteLine($"The value of PI is: {PI}");
Type Conversion
C# provides various methods to convert data types:
// Implicit conversion
int num = 10;
double doubleNum = num; // No explicit conversion needed
// Explicit conversion (casting)
double doubleValue = 10.7;
int intValue = (int)doubleValue; // Value becomes 10 (truncated)
Console.WriteLine($"Double {doubleValue} cast to int: {intValue}");
// Using Convert class
string numberString = "100";
int convertedNumber = Convert.ToInt32(numberString);
Console.WriteLine($"Converted string to number: {convertedNumber}");
// Using Parse method
string anotherNumber = "200";
int parsedNumber = int.Parse(anotherNumber);
Console.WriteLine($"Parsed string to number: {parsedNumber}");
Operators
C# supports various operators for different operations:
// Arithmetic operators
int a = 10, b = 3;
Console.WriteLine($"Addition: {a + b}");
Console.WriteLine($"Subtraction: {a - b}");
Console.WriteLine($"Multiplication: {a * b}");
Console.WriteLine($"Division: {a / b}");
Console.WriteLine($"Modulus: {a % b}");
// Comparison operators
Console.WriteLine($"Equal to: {a == b}");
Console.WriteLine($"Not equal to: {a != b}");
Console.WriteLine($"Greater than: {a > b}");
Console.WriteLine($"Less than: {a < b}");
// Logical operators
bool x = true, y = false;
Console.WriteLine($"AND: {x && y}");
Console.WriteLine($"OR: {x || y}");
Console.WriteLine($"NOT: {!x}");
Control Structures
Conditional Statements
int age = 20;
// If statement
if (age >= 18)
{
Console.WriteLine("You are an adult");
}
else if (age >= 13)
{
Console.WriteLine("You are a teenager");
}
else
{
Console.WriteLine("You are a child");
}
// Switch statement
string day = "Monday";
switch (day)
{
case "Monday":
Console.WriteLine("Start of work week");
break;
case "Friday":
Console.WriteLine("End of work week");
break;
case "Saturday":
case "Sunday":
Console.WriteLine("Weekend!");
break;
default:
Console.WriteLine("Midweek");
break;
}
// Ternary operator
string status = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine($"Status: {status}");
Loops
C# provides several looping structures:
// For loop
Console.WriteLine("For loop:");
for (int i = 0; i < 5; i++)
{
Console.Write($"{i} ");
}
Console.WriteLine();
// While loop
Console.WriteLine("While loop:");
int counter = 0;
while (counter < 5)
{
Console.Write($"{counter} ");
counter++;
}
Console.WriteLine();
// Do-while loop
Console.WriteLine("Do-while loop:");
int j = 0;
do
{
Console.Write($"{j} ");
j++;
} while (j < 5);
Console.WriteLine();
// Foreach loop (iterating through a collection)
Console.WriteLine("Foreach loop:");
string[] fruits = { "Apple", "Banana", "Cherry", "Date" };
foreach (string fruit in fruits)
{
Console.Write($"{fruit} ");
}
Console.WriteLine();
Output:
For loop:
0 1 2 3 4
While loop:
0 1 2 3 4
Do-while loop:
0 1 2 3 4
Foreach loop:
Apple Banana Cherry Date
Methods (Functions)
Methods are blocks of code that perform specific tasks.
// Method with no parameters and no return value
static void SayHello()
{
Console.WriteLine("Hello!");
}
// Method with parameters
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
// Method with parameters and return value
static int Add(int a, int b)
{
return a + b;
}
// Method with optional parameters
static void DisplayInfo(string name, int age = 30)
{
Console.WriteLine($"{name} is {age} years old");
}
// Using these methods
static void Main(string[] args)
{
SayHello(); // Output: Hello!
Greet("Alice"); // Output: Hello, Alice!
int sum = Add(5, 3);
Console.WriteLine($"Sum: {sum}"); // Output: Sum: 8
DisplayInfo("Bob"); // Output: Bob is 30 years old
DisplayInfo("Charlie", 25); // Output: Charlie is 25 years old
}
Arrays and Collections
Arrays
Arrays store multiple values of the same type in a single variable.
// Declare and initialize an array
int[] numbers = { 1, 2, 3, 4, 5 };
// Access array elements
Console.WriteLine($"First number: {numbers[0]}");
Console.WriteLine($"Third number: {numbers[2]}");
// Change array element
numbers[1] = 10;
Console.WriteLine($"Updated second number: {numbers[1]}");
// Array length
Console.WriteLine($"Array length: {numbers.Length}");
// Iterate through an array
Console.WriteLine("All numbers:");
foreach (int num in numbers)
{
Console.Write($"{num} ");
}
Console.WriteLine();
// Multi-dimensional array
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Console.WriteLine($"Matrix element [1,2]: {matrix[1, 2]}");
Lists
Lists are dynamic collections that can grow as needed.
using System.Collections.Generic;
// Create a list of strings
List<string> cities = new List<string> { "New York", "London", "Tokyo" };
// Add items to a list
cities.Add("Paris");
cities.Add("Berlin");
// Access items
Console.WriteLine($"First city: {cities[0]}");
// Check if an item exists
bool containsTokyo = cities.Contains("Tokyo");
Console.WriteLine($"Contains Tokyo: {containsTokyo}");
// Remove an item
cities.Remove("London");
// List count
Console.WriteLine($"Number of cities: {cities.Count}");
// Iterate through a list
Console.WriteLine("All cities:");
foreach (string city in cities)
{
Console.WriteLine(city);
}
Object-Oriented Programming Basics
Classes and Objects
C# is an object-oriented programming language where classes are blueprints for objects.
// Define a class
public class Person
{
// Fields
private string name;
private int age;
// Constructor
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
// Methods
public void Introduce()
{
Console.WriteLine($"Hi, I'm {name} and I'm {age} years old.");
}
public void CelebrateBirthday()
{
age++;
Console.WriteLine($"{name} is now {age} years old!");
}
}
// Using the class
static void Main(string[] args)
{
// Create objects
Person person1 = new Person("John", 25);
Person person2 = new Person("Sarah", 30);
// Call methods
person1.Introduce(); // Output: Hi, I'm John and I'm 25 years old.
person2.Introduce(); // Output: Hi, I'm Sarah and I'm 30 years old.
person1.CelebrateBirthday(); // Output: John is now 26 years old!
}
Properties
Properties provide a flexible mechanism to read, write, or compute the value of private fields.
public class Student
{
// Private field
private string name;
// Property with get and set accessors
public string Name
{
get { return name; }
set { name = value; }
}
// Auto-implemented property
public int Age { get; set; }
// Read-only property
public bool IsAdult
{
get { return Age >= 18; }
}
}
// Using properties
Student student = new Student();
student.Name = "Alice"; // Set property
student.Age = 20; // Set auto-property
Console.WriteLine($"Name: {student.Name}"); // Get property
Console.WriteLine($"Age: {student.Age}"); // Get auto-property
Console.WriteLine($"Is adult: {student.IsAdult}"); // Get read-only property
Exception Handling
Exception handling allows you to gracefully handle errors in your C# programs.
try
{
// Code that might throw an exception
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int number = int.Parse(input);
Console.WriteLine($"You entered: {number}");
// Division that might cause division by zero
int result = 100 / number;
Console.WriteLine($"100 divided by {number} is {result}");
}
catch (FormatException ex)
{
// Handle format exception
Console.WriteLine("Error: You did not enter a valid number.");
Console.WriteLine($"Exception details: {ex.Message}");
}
catch (DivideByZeroException ex)
{
// Handle division by zero
Console.WriteLine("Error: Cannot divide by zero.");
Console.WriteLine($"Exception details: {ex.Message}");
}
catch (Exception ex)
{
// Handle any other exception
Console.WriteLine("An unexpected error occurred.");
Console.WriteLine($"Exception details: {ex.Message}");
}
finally
{
// Code that always runs
Console.WriteLine("This code always runs, regardless of exceptions.");
}
A Real-World Example: Simple Student Management System
Let's create a practical example that brings together many of the concepts we've covered:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StudentManagementSystem
{
public class Student
{
// Properties
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<int> Grades { get; private set; }
// Constructor
public Student(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
Grades = new List<int>();
}
// Methods
public void AddGrade(int grade)
{
if (grade < 0 || grade > 100)
{
throw new ArgumentException("Grade must be between 0 and 100");
}
Grades.Add(grade);
}
public double GetAverageGrade()
{
if (Grades.Count == 0)
return 0;
return Grades.Average();
}
public string GetSummary()
{
return $"Student {Id}: {Name}, Age: {Age}, Average Grade: {GetAverageGrade():F1}";
}
}
public class StudentManager
{
private List<Student> students;
public StudentManager()
{
students = new List<Student>();
}
public void AddStudent(Student student)
{
students.Add(student);
}
public Student FindStudent(int id)
{
return students.FirstOrDefault(s => s.Id == id);
}
public void DisplayAllStudents()
{
if (students.Count == 0)
{
Console.WriteLine("No students registered.");
return;
}
foreach (var student in students)
{
Console.WriteLine(student.GetSummary());
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Student Management System");
Console.WriteLine("========================");
StudentManager manager = new StudentManager();
try
{
// Add some students
Student s1 = new Student(1, "Alice Smith", 20);
s1.AddGrade(85);
s1.AddGrade(90);
s1.AddGrade(78);
manager.AddStudent(s1);
Student s2 = new Student(2, "Bob Johnson", 22);
s2.AddGrade(76);
s2.AddGrade(82);
s2.AddGrade(94);
manager.AddStudent(s2);
Student s3 = new Student(3, "Charlie Brown", 19);
s3.AddGrade(90);
s3.AddGrade(92);
s3.AddGrade(88);
manager.AddStudent(s3);
// Display all students
Console.WriteLine("\nAll Students:");
manager.DisplayAllStudents();
// Find and display a specific student
Console.WriteLine("\nSearching for student with ID 2:");
Student found = manager.FindStudent(2);
if (found != null)
{
Console.WriteLine(found.GetSummary());
// Add another grade
found.AddGrade(88);
Console.WriteLine("Added a new grade (88)");
Console.WriteLine(found.GetSummary());
}
else
{
Console.WriteLine("Student not found.");
}
// Try to add an invalid grade
Console.WriteLine("\nTrying to add an invalid grade:");
manager.FindStudent(1).AddGrade(105); // This will throw an exception
}
catch (ArgumentException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}
}
Output:
Student Management System
========================
All Students:
Student 1: Alice Smith, Age: 20, Average Grade: 84.3
Student 2: Bob Johnson, Age: 22, Average Grade: 84.0
Student 3: Charlie Brown, Age: 19, Average Grade: 90.0
Searching for student with ID 2:
Student 2: Bob Johnson, Age: 22, Average Grade: 84.0
Added a new grade (88)
Student 2: Bob Johnson, Age: 22, Average Grade: 85.0
Trying to add an invalid grade:
Error: Grade must be between 0 and 100
Summary
In this tutorial, we've covered the fundamental concepts of C# programming, including:
- Basic syntax and data types
- Variables and constants
- Operators and control structures
- Methods and parameters
- Arrays and collections
- Classes, objects, and properties
- Exception handling
C# is a powerful and versatile language that forms the backbone of .NET development. The concepts we've explored provide a solid foundation for building sophisticated applications across various domains.
Additional Resources
To deepen your understanding of C# and .NET:
- Microsoft Documentation: C# Documentation
- C# Programming Guide: Microsoft Learn
- Interactive Learning: .NET Interactive Notebooks
- Practice Platforms:
Exercises
Test your understanding with these exercises:
- Create a C# console application that converts temperatures between Celsius and Fahrenheit.
- Build a simple calculator that can perform basic arithmetic operations.
- Create a program that reads a text file and counts the frequency of each word.
- Develop a banking system with classes for Account, Transaction, and Bank.
- Create a quiz application that reads questions and answers from a file and evaluates user responses.
Remember, the best way to learn programming is through practice. Start with small projects and gradually tackle more complex challenges as you become comfortable with C# syntax and concepts.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)