Skip to main content

.NET C# Syntax

Introduction

C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft as part of the .NET framework. It combines the power and flexibility of C++ with the simplicity of Visual Basic, making it an excellent language for beginners and experienced developers alike. This guide will walk you through the fundamental syntax elements of C# to help you start your programming journey.

C# is statically typed, meaning variable types are checked at compile time, which helps catch errors early. It also features automatic memory management through garbage collection, so you don't need to manually allocate and free memory as in languages like C or C++.

Basic Program Structure

Every C# program starts with a basic structure. Here's a simple "Hello World" example:

csharp
using System;

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

Output:

Hello, World!

Let's break down the components:

  • using System; - Imports the System namespace which contains fundamental classes like Console
  • namespace MyFirstProgram - Defines a namespace for your code to avoid naming conflicts
  • class Program - Creates a class which encapsulates your code
  • static void Main(string[] args) - The entry point method for your application
  • Console.WriteLine("Hello, World!"); - Outputs text to the console

Variables and Data Types

C# provides various data types for different kinds of values:

csharp
// Integer types
int age = 25; // 32-bit integer
long population = 8000000L; // 64-bit integer
short distance = 150; // 16-bit integer
byte level = 5; // 8-bit unsigned integer

// Floating-point types
float temperature = 23.5f; // 32-bit floating point
double pi = 3.14159; // 64-bit floating point
decimal price = 19.99m; // High-precision decimal

// Character and string types
char grade = 'A'; // Single character
string name = "Alice"; // String of characters

// Boolean type
bool isActive = true; // True or false value

// Display some values
Console.WriteLine($"Name: {name}, Age: {age}");
Console.WriteLine($"Is active: {isActive}");
Console.WriteLine($"Price: ${price}");

Output:

Name: Alice, Age: 25
Is active: True
Price: $19.99

Variable Declaration

Variables in C# must be declared before use:

csharp
// Explicit type declaration
int count = 10;

// Type inference with 'var' keyword (compiler determines the type)
var message = "Hello there"; // Compiler infers string type
var number = 42; // Compiler infers int type

// Constants (values that cannot change)
const double GravitationalConstant = 6.67430e-11;

Operators

C# supports various operators for arithmetic, comparison, logical operations, and more:

Arithmetic Operators

csharp
int a = 10;
int b = 3;

int sum = a + b; // Addition: 13
int difference = a - b; // Subtraction: 7
int product = a * b; // Multiplication: 30
int quotient = a / b; // Division: 3 (integer division)
int remainder = a % b; // Modulus: 1

Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Difference: {difference}");
Console.WriteLine($"Product: {product}");
Console.WriteLine($"Quotient: {quotient}");
Console.WriteLine($"Remainder: {remainder}");

Output:

Sum: 13
Difference: 7
Product: 30
Quotient: 3
Remainder: 1

Comparison Operators

csharp
int x = 5;
int y = 8;

bool isEqual = x == y; // Equal to: false
bool isNotEqual = x != y; // Not equal to: true
bool isGreater = x > y; // Greater than: false
bool isLess = x < y; // Less than: true
bool isGreaterOrEqual = x >= y; // Greater than or equal to: false
bool isLessOrEqual = x <= y; // Less than or equal to: true

Console.WriteLine($"x equals y: {isEqual}");
Console.WriteLine($"x not equal to y: {isNotEqual}");
Console.WriteLine($"x greater than y: {isGreater}");
Console.WriteLine($"x less than y: {isLess}");

Output:

x equals y: False
x not equal to y: True
x greater than y: False
x less than y: True

Logical Operators

csharp
bool condition1 = true;
bool condition2 = false;

bool andResult = condition1 && condition2; // Logical AND: false
bool orResult = condition1 || condition2; // Logical OR: true
bool notResult = !condition1; // Logical NOT: false

Console.WriteLine($"AND result: {andResult}");
Console.WriteLine($"OR result: {orResult}");
Console.WriteLine($"NOT result: {notResult}");

Output:

AND result: False
OR result: True
NOT result: False

Control Flow

Conditional Statements

If-Else Statement

csharp
int hour = 14;

if (hour < 12)
{
Console.WriteLine("Good morning!");
}
else if (hour < 18)
{
Console.WriteLine("Good afternoon!");
}
else
{
Console.WriteLine("Good evening!");
}

Output:

Good afternoon!

Switch Statement

csharp
int day = 3;
string dayName;

switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}

Console.WriteLine($"Day {day} is {dayName}");

Output:

Day 3 is Wednesday

Loops

For Loop

csharp
Console.WriteLine("Counting from 1 to 5 using for loop:");
for (int i = 1; i <= 5; i++)
{
Console.Write($"{i} ");
}
Console.WriteLine();

Output:

Counting from 1 to 5 using for loop:
1 2 3 4 5

While Loop

csharp
Console.WriteLine("Counting from 5 to 1 using while loop:");
int counter = 5;
while (counter > 0)
{
Console.Write($"{counter} ");
counter--;
}
Console.WriteLine();

Output:

Counting from 5 to 1 using while loop:
5 4 3 2 1

Do-While Loop

csharp
Console.WriteLine("Using do-while loop to ask for input:");
string input;
do
{
Console.Write("Type 'exit' to quit: ");
input = "exit"; // In a real program, you'd use Console.ReadLine()
} while (input != "exit");

Console.WriteLine("Exited the loop!");

Output:

Using do-while loop to ask for input:
Type 'exit' to quit: Exited the loop!

Foreach Loop

csharp
Console.WriteLine("Iterating through an array using foreach:");
string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };

foreach (string fruit in fruits)
{
Console.WriteLine($"- {fruit}");
}

Output:

Iterating through an array using foreach:
- Apple
- Banana
- Cherry
- Date
- Elderberry

Arrays and Collections

Arrays

csharp
// Declare and initialize an array
int[] numbers = { 10, 20, 30, 40, 50 };

// Access elements by index (zero-based)
Console.WriteLine($"First element: {numbers[0]}");
Console.WriteLine($"Third element: {numbers[2]}");

// Get the length of the array
Console.WriteLine($"Array length: {numbers.Length}");

// Modify an element
numbers[1] = 25;
Console.WriteLine($"Modified second element: {numbers[1]}");

// Declare an array without initializing
string[] names = new string[3];
names[0] = "John";
names[1] = "Jane";
names[2] = "Jim";

// Display all elements using foreach
foreach (string name in names)
{
Console.WriteLine(name);
}

Output:

First element: 10
Third element: 30
Array length: 5
Modified second element: 25
John
Jane
Jim

Lists

Lists are dynamic arrays that can grow or shrink in size:

csharp
using System.Collections.Generic;

// Create a list of strings
List<string> cities = new List<string>();

// Add elements
cities.Add("New York");
cities.Add("London");
cities.Add("Tokyo");
cities.Add("Paris");

// Access elements by index
Console.WriteLine($"First city: {cities[0]}");

// Count elements
Console.WriteLine($"Number of cities: {cities.Count}");

// Check if an element exists
bool containsLondon = cities.Contains("London");
Console.WriteLine($"Contains London: {containsLondon}");

// Remove an element
cities.Remove("Tokyo");
Console.WriteLine("After removing Tokyo:");

// Loop through the list
foreach (string city in cities)
{
Console.WriteLine($"- {city}");
}

Output:

First city: New York
Number of cities: 4
Contains London: True
After removing Tokyo:
- New York
- London
- Paris

Methods

Methods are blocks of code that perform specific tasks:

csharp
class Calculator
{
// Method with return value and parameters
public int Add(int a, int b)
{
return a + b;
}

// Method with void return type (returns nothing)
public void PrintSum(int a, int b)
{
int sum = Add(a, b);
Console.WriteLine($"The sum of {a} and {b} is {sum}");
}

// Method with optional parameters
public double CalculateInterest(double principal, double rate, int years = 1)
{
return principal * rate * years;
}

// Method with output parameters
public bool Divide(int dividend, int divisor, out int quotient, out int remainder)
{
if (divisor == 0)
{
quotient = 0;
remainder = 0;
return false;
}

quotient = dividend / divisor;
remainder = dividend % divisor;
return true;
}
}

// Usage example
Calculator calc = new Calculator();

// Calling a method that returns a value
int sum = calc.Add(15, 27);
Console.WriteLine($"15 + 27 = {sum}");

// Calling a void method
calc.PrintSum(8, 12);

// Using optional parameters
double interest1 = calc.CalculateInterest(1000, 0.05); // Uses default years = 1
double interest2 = calc.CalculateInterest(1000, 0.05, 3); // Specifies years = 3
Console.WriteLine($"Interest for 1 year: {interest1}");
Console.WriteLine($"Interest for 3 years: {interest2}");

// Using output parameters
bool success = calc.Divide(20, 7, out int result, out int remainder);
if (success)
{
Console.WriteLine($"20 ÷ 7 = {result} with remainder {remainder}");
}

Output:

15 + 27 = 42
The sum of 8 and 12 is 20
Interest for 1 year: 50
Interest for 3 years: 150
20 ÷ 7 = 2 with remainder 6

Classes and Objects

Classes are blueprints for creating objects, which are instances of a class:

csharp
// Define a class
class Person
{
// Fields (private by convention)
private string _name;
private int _age;

// Properties (public access to fields)
public string Name
{
get { return _name; }
set { _name = value; }
}

// Auto-implemented property (shorthand)
public int Age { get; set; }

// Read-only property
public bool IsAdult => Age >= 18;

// Constructor
public Person(string name, int age)
{
_name = name;
Age = age; // Uses the auto-property setter
}

// Method
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}

// Create objects from the class
Person person1 = new Person("Alice", 28);
Person person2 = new Person("Bob", 17);

// Access properties
Console.WriteLine($"{person1.Name} is {person1.Age} years old.");
Console.WriteLine($"Is {person1.Name} an adult? {person1.IsAdult}");
Console.WriteLine($"Is {person2.Name} an adult? {person2.IsAdult}");

// Call methods
person1.Introduce();
person2.Introduce();

// Modify properties
person2.Name = "Bobby";
person2.Age = 18;
person2.Introduce();

Output:

Alice is 28 years old.
Is Alice an adult? True
Is Bob an adult? False
Hello, my name is Alice and I am 28 years old.
Hello, my name is Bob and I am 17 years old.
Hello, my name is Bobby and I am 18 years old.

Real-World Application: Simple Banking System

Let's combine multiple concepts to create a simple banking system:

csharp
using System;
using System.Collections.Generic;

class BankAccount
{
// Properties
public string AccountNumber { get; }
public string OwnerName { get; }
private double _balance;
public double Balance
{
get { return _balance; }
private set { _balance = value; }
}

// Transaction history
private List<string> _transactions;

// Constructor
public BankAccount(string ownerName, string accountNumber, double initialDeposit)
{
OwnerName = ownerName;
AccountNumber = accountNumber;
Balance = initialDeposit;
_transactions = new List<string>();

RecordTransaction($"Initial deposit: ${initialDeposit}");
}

// Methods
public void Deposit(double amount)
{
if (amount <= 0)
{
Console.WriteLine("Error: Deposit amount must be positive");
return;
}

Balance += amount;
RecordTransaction($"Deposit: ${amount}");
Console.WriteLine($"Successfully deposited ${amount}. New balance: ${Balance}");
}

public bool Withdraw(double amount)
{
if (amount <= 0)
{
Console.WriteLine("Error: Withdrawal amount must be positive");
return false;
}

if (amount > Balance)
{
Console.WriteLine("Error: Insufficient funds");
return false;
}

Balance -= amount;
RecordTransaction($"Withdrawal: ${amount}");
Console.WriteLine($"Successfully withdrew ${amount}. New balance: ${Balance}");
return true;
}

public void PrintStatement()
{
Console.WriteLine($"\nAccount Statement for {OwnerName}");
Console.WriteLine($"Account Number: {AccountNumber}");
Console.WriteLine($"Current Balance: ${Balance}");

Console.WriteLine("\nTransaction History:");
foreach (string transaction in _transactions)
{
Console.WriteLine($"- {transaction}");
}
Console.WriteLine();
}

private void RecordTransaction(string description)
{
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
_transactions.Add($"{timestamp} - {description}");
}
}

// Example usage
BankAccount account = new BankAccount("John Smith", "1234567890", 1000.00);

account.Deposit(500.50);
account.Withdraw(200.00);
account.Withdraw(2000.00); // Should fail
account.Deposit(150.25);

account.PrintStatement();

Output:

Successfully deposited $500.5. New balance: $1500.5
Successfully withdrew $200. New balance: $1300.5
Error: Insufficient funds
Successfully deposited $150.25. New balance: $1450.75

Account Statement for John Smith
Account Number: 1234567890
Current Balance: $1450.75

Transaction History:
- 2023-05-10 15:30:22 - Initial deposit: $1000
- 2023-05-10 15:30:22 - Deposit: $500.5
- 2023-05-10 15:30:22 - Withdrawal: $200
- 2023-05-10 15:30:22 - Deposit: $150.25

Summary

In this guide, we've covered the essential syntax elements of C# in the .NET framework:

  • Basic program structure with namespaces, classes, and methods
  • Variables, data types, and operators
  • Control flow statements including conditionals and loops
  • Arrays and collections for working with groups of data
  • Methods for organizing code into reusable blocks
  • Classes and objects for object-oriented programming

This foundation will help you start building your own C# applications within the .NET ecosystem. As you grow more comfortable with these basics, you can explore more advanced topics such as inheritance, interfaces, exception handling, LINQ queries, asynchronous programming, and more.

Additional Resources

  1. Microsoft Documentation: C# Documentation
  2. C# Programming Guide: Microsoft Learn
  3. Interactive Learning: Try .NET
  4. Video Tutorials: Microsoft's C# 101 Series

Exercises

To practice your C# skills, try these exercises:

  1. Temperature Converter: Write a program that converts temperatures between Celsius and Fahrenheit.
  2. Number Guessing Game: Create a game that generates a random number and asks the user to guess it, providing hints if the guess is too high or too low.
  3. To-Do List Manager: Build a simple console application that allows users to add, remove, and view tasks in a to-do list.
  4. Student Grade Tracker: Develop a program that tracks student names and grades, calculates averages, and displays statistics.
  5. Bank Account Manager: Extend the banking example to support multiple accounts and transfers between accounts.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)