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
}
}
}
using System;
namespace FirstNamespace
{
// Class in the first namespace
public class FirstClass
{
public void DisplayMessage()
{
Console.WriteLine("Hello from the First Namespace!");
}
}
}
namespace SecondNamespace
{
// Class in the second namespace
public class SecondClass
{
public void ShowMessage()
{
Console.WriteLine("Hello from the Second Namespace!");
}
// Method to call a method from FirstNamespace
public void CallFirstNamespaceMethod()
{
FirstNamespace.FirstClass firstClassObj = new FirstNamespace.FirstClass();
firstClassObj.DisplayMessage();
}
}
}
class Program
{
static void Main(string[] args)
{
// Creating an object of the SecondClass
SecondNamespace.SecondClass secondClassObj = new SecondNamespace.SecondClass();
// Call method of SecondNamespace
secondClassObj.ShowMessage();
// Call method from FirstNamespace through SecondNamespace
secondClassObj.CallFirstNamespaceMethod();
Console.ReadLine(); // Keep the console open
}
}
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
float temperature = 36.6f; // Float type for single-precision floating-point numbers
bool isEmployed = true; // Boolean type (true or false)
Note: In C#, public methods and built-in method names (such as Console.WriteLine()) typically follow the PascalCase convention, where each word starts with a capital letter. However, not all function names are capitalized. Private or internal methods often follow the camelCase convention, where the first word starts with a lowercase letter and subsequent words are capitalized. This helps distinguish between public and private members in a class.
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!
Common String Operations
Combining two or more strings. You can use the + operator or the String.Concat() method.
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // John Doe
// OR
string fullName = String.Concat(firstName, " ", lastName);
Extracts a portion of the string based on starting position and length.
string sentence = "Hello, World!";
string sub = sentence.Substring(7, 5); // Output: World
Returns the number of characters in the string.
int length = fullName.Length; // Output: 8 for "John Doe"
Inserting variables inside a string using the $ symbol.
string greeting = $"Hello, {firstName} {lastName}!";
Convert a string to uppercase or lowercase.
string lower = fullName.ToLower(); // john doe
string upper = fullName.ToUpper(); // JOHN DOE
Replaces occurrences of a specified character or substring.
string replaced = fullName.Replace("Doe", "Smith"); // John Smith
Splits a string into an array of substrings based on a delimiter.
string names = "John,Doe,Jane";
string[] nameArray = names.Split(','); // ["John", "Doe", "Jane"]
Removes leading and trailing white spaces.
string trimmed = " Hello ".Trim(); // Output: "Hello"
Checks for substring or how a string starts or ends.
bool contains = fullName.Contains("John"); // true
bool starts = fullName.StartsWith("John"); // true
bool ends = fullName.EndsWith("Doe"); // true
Use Equals or CompareTo methods to compare two strings.
bool areEqual = firstName.Equals("John"); // true
int comparison = firstName.CompareTo(lastName); // Negative value as "John" comes before "Doe"
In C#, date and time are represented by the DateTime struct. It can store both date and time.
Date Input and Parsing in C#
When we input a date from the user in C#, we typically collect it as a string and then convert (parse) that string into a DateTime object. This is necessary because user input is always received as text, and we need to convert it into the appropriate data type for further operations.
Example of getting a date input:
Console.Write("Enter a date (yyyy-mm-dd): ");
string dateInput = Console.ReadLine();
To convert a date string into a DateTime object, C# provides several methods for parsing. Parsing is the process of converting a string that represents a date into a structured DateTime object.
DateTime.Parse()
DateTime.Parse() is used to parse a string into a DateTime object. It assumes the string is formatted correctly, and if it is not, the program will throw an exception.
Example:
string dateInput = "2024-10-04";
DateTime parsedDate = DateTime.Parse(dateInput);
Console.WriteLine("Parsed Date: " + parsedDate.ToString("yyyy-MM-dd"));
In date formatting, "MM" and "mm" have different meanings in C# (and in most other date/time formatting systems):
Important Considerations:
DateTime.TryParse()
DateTime.TryParse() is a safer alternative that attempts to parse the date and returns a boolean result indicating success or failure. It doesn’t throw an exception if the parsing fails, so it is ideal for user input scenarios.
Example:
string dateInput = "2024-10-04";
DateTime userDate;
bool isDateValid = DateTime.TryParse(dateInput, out userDate);
if (isDateValid)
{
Console.WriteLine("Valid Date: " + userDate.ToString("yyyy-MM-dd"));
}
else
{
Console.WriteLine("Invalid date format.");
}
Why Use TryParse:
How to Define a Date
DateTime now = DateTime.Now; // Current date and time
DateTime specificDate = new DateTime(2023, 10, 4); // Year, Month, Day
Common Date Operations
You can format a date into different string representations.
string formattedDate = now.ToString("MM/dd/yyyy"); // Output: 10/04/2024
Methods like AddDays(), AddMonths(), and AddYears() are used for date arithmetic.
DateTime futureDate = now.AddDays(5); // Adds 5 days to current date
DateTime pastDate = now.AddMonths(-2); // Subtracts 2 months from current date
Dates can be compared using comparison operators or the CompareTo method.
if (now > specificDate) {
// now is later than specificDate
}
int comparison = now.CompareTo(specificDate); // 0: equal, 1: later, -1: earlier
You can retrieve the year, month, day, etc., from a DateTime object.
int year = now.Year; // Output: 2024
int month = now.Month; // Output: 10
int day = now.Day; // Output: 4
Use TimeSpan to calculate the difference between two dates.
DateTime date1 = new DateTime(2024, 10, 1);
DateTime date2 = new DateTime(2024, 10, 4);
TimeSpan difference = date2 - date1; // Output: 3 days
Convert a string into a DateTime object using DateTime.Parse() or DateTime.TryParse().
DateTime parsedDate = DateTime.Parse("2024-10-04");
You can use DateTime.Today to get the current date without the time component.
DateTime today = DateTime.Today; // Current date without time
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
float floatValue = Convert.ToSingle(strNum); // Converts string to float
bool boolValue = Convert.ToBoolean("true"); // Converts string to boolean
long longValue = Convert.ToInt64(strNum); // Converts string to long
// 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.");
}
}
}