Understanding the basic syntax of C# is crucial for writing efficient code. Below are the main elements of C# syntax:
A simple C# program consists of several components:
using System; // Namespace declaration
namespace HelloWorldApp // Namespace definition
{
class Program // Class declaration
{
static void Main(string[] args) // Main method (entry point of the program)
{
Console.WriteLine("Hello, World!"); // Output statement
}
}
}
Variables are used to store data in a program. C# is a strongly-typed language, meaning you must declare the type of data a variable will hold. Each variable is associated with a specific data type that determines the kind of values it can store and what operations can be performed on them.
// Examples of variable declarations in C#
int age = 25; // Integer type
string name = "John"; // String type
double salary = 5000.50; // Double type for floating-point numbers
bool isEmployed = true; // Boolean type (true or false)
Strings in C# are sequences of characters used to represent text. You can manipulate strings using various methods provided by the string class.
// Example of working with strings
string greeting = "Hello, World!";
string upperCaseGreeting = greeting.ToUpper(); // Converts string to uppercase
Console.WriteLine(upperCaseGreeting); // Output: HELLO, WORLD!
In C#, the DateTime structure is used to represent dates and times. You can retrieve the current date and time, format dates, and perform date arithmetic.
// Example of working with DateTime
DateTime currentDate = DateTime.Now; // Gets the current date and time
DateTime birthDate = new DateTime(1990, 5, 15); // Specifies a custom date
TimeSpan ageSpan = currentDate - birthDate; // Calculates the difference between two dates
int age = ageSpan.Days / 365; // Convert the difference to years
Console.WriteLine($"Your age is {age} years."); // Output: Your age is (calculated age) years
Data type conversion allows transforming one data type into another. C# provides multiple ways to
perform conversions, including implicit and explicit conversion, methods like
Convert
and
// Implicit conversion example
int intNum = 10;
double doubleNum = intNum; // No need for casting, happens automatically
// Explicit conversion example
double doubleNum = 10.5;
int intNum = (int)doubleNum; // Cast explicitly, results in 10 (fractional part lost)
// Example of using Convert methods
string strNum = "123";
int num = Convert.ToInt32(strNum); // Converts string to integer
double doubleValue = Convert.ToDouble(strNum); // Converts string to double
// Example of using Parse method
string strNum = "456";
int num = int.Parse(strNum); // Converts string to integer
Console.WriteLine(num); // Output: 456
string strDecimal = "123.45";
double doubleValue = double.Parse(strDecimal); // Converts string to double
Console.WriteLine(doubleValue); // Output: 123.45
// Example of using TryParse method
string strNum = "789";
int result;
bool isParsed = int.TryParse(strNum, out result); // Returns true if successful
Console.WriteLine(isParsed ? $"Parsed: {result}" : "Failed to parse"); // Output: Parsed: 789
Comments are used to explain code and are ignored by the compiler. There are two types of comments in C#:
// This is a single-line comment
/*
This is a
multi-line comment
*/
C# supports various operators for performing calculations and comparisons.
Control statements are fundamental constructs in programming used to dictate the flow of execution based on certain conditions or to repeat blocks of code. Understanding these statements is crucial for developing effective and efficient code.
Conditional statements allow the program to execute different sections of code based on certain conditions.
int age = 20;
if (age > 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are not an adult.");
}
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else
{
Console.WriteLine("Grade: C");
}
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Loops are used to execute a block of code repeatedly based on a condition or a specified number of iterations.
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Iteration: " + i);
}
int i = 0;
while (i < 5)
{
Console.WriteLine("Iteration: " + i);
i++;
}
int i = 0;
do
{
Console.WriteLine("Iteration: " + i);
i++;
}
while (i < 5);
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
Console.WriteLine("Name: " + name);
}
Functions are reusable blocks of code that perform a specific task.
void SayHello() // Function definition
{
Console.WriteLine("Hello, World!");
}
SayHello(); // Function call
Classes are blueprints for creating objects, and objects are instances of classes.
class Person // Class definition
{
public string Name; // Field
public void Greet() // Method
{
Console.WriteLine("Hello, my name is " + Name);
}
}
Person person1 = new Person(); // Create object
person1.Name = "John"; // Assign value
person1.Greet(); // Call method
Input and output operations are fundamental to interacting with users and handling data in C# programs. Understanding these operations is crucial for developing applications that can receive input from users and display output effectively.
Output operations are used to display information to the user. The most common methods for outputting data in C# are `Console.WriteLine()`, `Console.Write()`, and `string.Format()`.
Console.WriteLine("Hello, World!");
Console.WriteLine("The result is: " + result);
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Hello, " + name + "!");
int age = 25;
Console.WriteLine("You are {0} years old.", age);
string name = "Alice";
Console.WriteLine("Hello, {0}!", name);
Input operations are used to receive data from the user. The primary method for reading input in C# is `Console.ReadLine()`, which reads a line of text from the console.
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int age = int.Parse(ageInput);
Console.WriteLine("You are " + age + " years old.");
Here are some basic examples demonstrating how to use these I/O methods in practice.
using System;
class Program
{
static void Main()
{
// Output
Console.WriteLine("Welcome to the C# program!");
// Input
Console.Write("Enter your favorite color: ");
string color = Console.ReadLine();
// Output with variable
Console.WriteLine("Your favorite color is " + color + ".");
}
}
using System;
class Program
{
static void Main()
{
// Output
Console.Write("Enter your birth year: ");
string yearInput = Console.ReadLine();
// Convert and calculate
int birthYear = int.Parse(yearInput);
int currentYear = DateTime.Now.Year;
int age = currentYear - birthYear;
// Output result
Console.WriteLine("You are " + age + " years old.");
}
}
using System;
class Program
{
static void Main()
{
// Output message to prompt user for input
Console.WriteLine("Enter the first number:");
// Read the first number as a string and convert it to an integer
string input1 = Console.ReadLine();
int number1 = int.Parse(input1);
// Output message to prompt user for the second number
Console.WriteLine("Enter the second number:");
// Read the second number as a string and convert it to an integer
string input2 = Console.ReadLine();
int number2 = int.Parse(input2);
// Calculate the sum of the two numbers
int sum = number1 + number2;
// Output the result
Console.WriteLine("The sum of {0} and {1} is {2}.", number1, number2, sum);
}
}
Arrays are a collection of items stored at contiguous memory locations. In C#, arrays are used to store multiple values of the same type in a single variable.
Before using arrays, you need to declare and initialize them. Here’s how:
int[] numbers; // Declares an array of integers
numbers = new int[5]; // Initializes an array with 5 elements
// Alternatively, you can declare and initialize in one line:
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
int firstNumber = numbers[0]; // Accesses the first element
numbers[1] = 10; // Modifies the second element
You can use loops to iterate through all elements of an array. The most common loop for this purpose is the for loop:
int[] numbers = { 10, 20, 30, 40, 50 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
C# supports several types of arrays:
int[] singleDimArray = { 10, 20, 30, 40, 50 };
int[,] multiDimArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
This program calculates the sum of all elements in an array.
using System;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = 0;
foreach (int number in numbers)
{
sum += number;
}
Console.WriteLine("Sum of array elements: " + sum);
}
}
This program searches for a specific element in the array and prints its index.
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
int searchElement = 30;
int index = -1;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == searchElement)
{
index = i;
break;
}
}
if (index != -1)
{
Console.WriteLine("Element found at index: " + index);
}
else
{
Console.WriteLine("Element not found.");
}
}
}