Unit-1
Unit-1
Introduction to C#
C# (pronounced "C-sharp") is a modern, high-level, object-oriented programming language developed
by Microsoft. It was first introduced in the early 2000s as part of the .NET platform and has since
become one of the most popular and widely used programming languages in the world. C# is known
for its versatility, robustness, and ease of use, making it a preferred choice for a wide range of
software development tasks.
C# is pronounced "C-Sharp".
C# has roots from the C family, and the language is close to other popular languages
like C++ and Java.
The first version was released in year 2002. The latest version, C# 11, was released in November
2022.
C# is used for:
Mobile applications
Desktop applications
Web applications
Web services
Web sites
Games
Database applications
And much, much more!
C# IDE
The easiest way to get started with C# is to use an IDE.
Applications written in C# use the .NET Framework, so it makes sense to use Visual Studio, as
the program, the framework, and the language, are all created by Microsoft.
Features of C-Sharp:
• Type Safety: C# is statically typed, which means that variable types are determined at
compile-time. This helps catch type-related errors before the program runs, making it more
reliable.
• Cross-Platform Development: With the introduction of .NET Core (now .NET 5 and later),
C# applications can be developed to run on multiple platforms, including Windows, macOS,
and Linux. This makes it suitable for cross-platform development.
• Rich Standard Library: C# is part of the .NET ecosystem, which includes a comprehensive
standard library known as the .NET Framework (or .NET Core/.NET 5+). This library
provides a wide range of pre-built classes and functions for common tasks, such as file I/O,
networking, and data manipulation.
• Modern Language Features: C# incorporates modern language features, including support for
asynchronous programming, lambda expressions, and LINQ (Language Integrated Query),
which make it expressive and efficient.
• Strong Community and Ecosystem: C# has a strong developer community and a vast
ecosystem of libraries, frameworks, and third-party tools, which simplifies development and
extends its capabilities.
• C# is a versatile and powerful programming language suitable for a wide range of application
development scenarios, including web development, desktop applications, mobile apps, cloud
services, and game development. Its combination of strong typing, modern features, and a
robust ecosystem has contributed to its popularity among developers worldwide.
C# Syntax
Using system;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.writeline(“Hello world”);
}
}
}
Line 1: using System means that we can use classes from the System namespace.
Line 2: A blank line. C# ignores white space. However, multiple lines makes the code more
readable.
Line 3: namespace is used to organize your code, and it is a container for classes and other
namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to your program.
Every line of code that runs in C# must be inside a class.
Line 7: Another thing that always appear in a C# program, is the Main method. Any code inside
its curly brackets {} will be executed. You don't have to understand the keywords before and
after Main. You will get to know them bit by bit while reading this tutorial.
Line 9: Console is a class of the System namespace, which has a WriteLine() method that is
used to output/print text.
If you omit the using System line, you would have to write System.Console.WriteLine() to
print/output text.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by C# (will not be executed).
C# Multi-line Comments
Multi-line comments start with /* and ends with */.
C# Variables
Variables are containers for storing data values.
In C#, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
Char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
String - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
C# Identifiers
The general rules for naming variables are:
Names can contain letters, digits and the underscore character (_)
Names must begin with a letter or underscore
Names should start with a lowercase letter and it cannot contain whitespace
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like C# keywords, such as int or double) cannot be used as names
C# Data Types
A data type specifies the size and type of variable values.
It is important to use the correct data type for the corresponding variable; to avoid errors, to save
time and memory, but it will also make your code more maintainable and readable. The most
common data types are:
Double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are int and long. Which type you should use, depends on the numeric
value.
Floating point types represents numbers with a fractional part, containing one or more decimals.
Integer Types
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in
our tutorial, the int data type is the preferred data type when we create variables with a numeric
value.
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that
you should end the value with an "L":
The float and double data types can store fractional numbers.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Example
float f1 = 35e3F;
double d1 = 12E4D;
Console.WriteLine(f1);
Console.WriteLine(d1);
Booleans
A boolean data type is declared with the bool keyword and can only take the values true or false
Characters
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c'
Strings
The string data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes
Operators
Operators are used to perform operations on variables and values.
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.
The return value of a comparison is either True or False. These values are known as Boolean
values.
!= Not equal x != y
Logical Operators
As with comparison operators, you can also test for True or False values with logical operators.
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns True if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns False if the result !(x < 5 && x <
is true 10)
Programs:
class Program
Console.WriteLine("Hello World!");
Console.ReadKey();
class Program
{
static void Main(string[] args)
{
int number;
Console.Write("Enter a number:");
number = Convert.ToInt32(Console.ReadLine());
class Program
{
static void Main(string[] args)
{
int num1, num2, sum;
Console.WriteLine("Calculate the sum of two numbers:");
Console.Write("Input number1:");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Input number2:");
num2 = Convert.ToInt32(Console.ReadLine());
sum = num1 + num2;
Console.Write("Result:"+sum);
Console.ReadKey();
}
}
4. C# Program to Multiply two Floating Point Numbers Entered by User
class Program
{
static void Main(string[] args)
{
float number1,number2,product;
Console.Write("Enter a number1:");
number1 = Convert.ToSingle(Console.ReadLine());
Console.Write("Enter a number2:");
number2 = Convert.ToSingle(Console.ReadLine());
int P, T;
float R, SI;
Console.Write("Enter Amount :");
P = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Rate :");
R = Convert.ToSingle(Console.ReadLine());
Console.Write("Enter Time :");
T = Convert.ToInt32(Console.ReadLine());
SI = P * R * T / 100;
Console.WriteLine("Interest is :{0}", SI);
Console.ReadKey();
Console.ReadLine();
class Program
{
static void Main(string[] args)
{
int area, length, width;
Console.Write("Please write the length of your rectangle: ");
length = Convert.ToInt32(Console.ReadLine());
Console.Write("Please write the width of your rectangle: ");
width = Convert.ToInt32(Console.ReadLine());
area = length * width;
Console.WriteLine("The area of rectangle : {0}", area);
Console.ReadKey();
}
}
7. C# Square Area and Perimeter Calculator
class Program
{
static void Main(string[] args)
{
int number1,number2,number3,avarage;
Console.ReadKey();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static long[] numbers;
static long Fib(int n)
{
if (0 == numbers[n])
{
numbers[n] = Fib(n - 1) + Fib(n - 2);
}
return numbers[n];
}
class Program
{
static void Main(string[] args)
{
int number, sum=0;
Console.ReadKey();
}
}
12. Get Month Name From Month Number – C#(Switch Case)
class Program
{
switch (monthNumber)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
case 3:
Console.WriteLine("March");
break;
case 4:
Console.WriteLine("April");
break;
case 5:
Console.WriteLine("May");
break;
case 6:
Console.WriteLine("June");
break;
case 7:
Console.WriteLine("July");
break;
case 8:
Console.WriteLine("August");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("October");
break;
case 11:
Console.WriteLine("November");
break;
case 12:
Console.WriteLine("December");
break;
default:
Console.WriteLine("you did not enter correct value for month name");
break;
}
Console.ReadLine();
}
}
13. Program to Find Leap Year in C#
1. Arithmetic Expressions:
- Arithmetic expressions involve mathematical operations like addition,
subtraction, multiplication, and division.
- Example:
```csharp
int result = 5 + 3; // Addition
```
2. Relational Expressions:
- Relational expressions compare values and return a Boolean result (true or
false).
- Example:
```csharp
bool isGreaterThan = 10 > 5; // Greater than comparison
```
3. Logical Expressions:
- Logical expressions combine Boolean values using logical operators like `&&`
(AND), `||` (OR), and `!` (NOT).
- Example:
```csharp
bool isTrue = true;
bool isFalse = !isTrue; // Logical NOT
```
5. Assignment Expressions:
- Assignment expressions assign a value to a variable.
- Example:
```csharp
int x = 10; // Simple assignment
```
```csharp
(parameters) => expression
```
- `parameters`: The input parameters (if any) that the lambda function takes. You
can have zero or more parameters enclosed in parentheses. For a single parameter,
you can omit the parentheses.
- `=>`: The lambda operator, which separates the parameter list from the
expression body.
- `expression`: The code to be executed when the lambda function is invoked. The
expression can be a single statement or a block of code enclosed in curly braces
`{}`.
This lambda function takes an integer `x` as a parameter and returns the square
of `x`. The `Func<int, int>` delegate type specifies that the lambda function takes
an integer and returns an integer.
```csharp
Func<int, int, int> add = (a, b) => a + b;
```
In this case, the lambda function takes two integer parameters, `a` and `b`, and
returns their sum.
```csharp
Action greet = () => Console.WriteLine("Hello, World!");
```
This lambda function takes no parameters and simply prints "Hello, World!"
when invoked.
```csharp
var evenNumbers = numbers.Where(x => x % 2 == 0);
```
Here, a lambda function is used in a LINQ `Where` method to filter out even
numbers from a collection of `numbers`.
Lambda functions are a powerful feature in C# that enables you to create small,
reusable, and concise pieces of code without the need for explicit method
declarations. They are widely used in modern C# programming, especially in
functional programming scenarios.
- Example:
```csharp
Func<int, int> square = x => x * x;
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Lambda expression to square a number
Func<int, int> square = x => x * x;
Console.WriteLine("Square of 5: " + square(5)); // Output: 25
Suppose you have a list of integers and want to filter out even numbers:
```csharp
var evenNumbers = numbers.Where(num => num % 2 == 0);
```
Suppose you have a collection of `Person` objects and want to find people older
than 30:
```csharp
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 28 },
new Person { Name = "Bob", Age = 35 },
new Person { Name = "Charlie", Age = 42 },
};
- Example:
```csharp
var query = from student in students
where student.Age > 18
select student.Name;
```
Branching:
Branching in C# refers to the ability to change the flow of program execution
based on certain conditions. It allows you to make decisions in your code and
execute different blocks of code depending on whether a condition is true or false.
C# provides several branching structures to accomplish this, including `if`
statements, `switch` statements, and loops.
1. If Statements:
- The `if` statement allows you to execute a block of code if a specified
condition is true.
```csharp
int age = 25;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
```
2. Else Statements:
- You can use an `else` statement to specify a block of code that is executed
when the condition in the `if` statement is false.
```csharp
int age = 15;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}
```
3. Else-If Statements:
- An `else if` statement allows you to specify multiple conditions to be tested
sequentially.
```csharp
int age = 30;
if (age < 18)
{
Console.WriteLine("You are a child.");
}
else if (age < 65)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a senior citizen.");
}
```
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
if (number % 2 == 0)
{
Console.WriteLine("{number} is even."+number);
}
else
{
Console.WriteLine($"{number} is odd.");
}
}
}
4. Switch Statements:
- The `switch` statement allows you to select one of many code blocks to be
executed.
```csharp
int dayOfWeek = 3;
switch (dayOfWeek)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
// ...
default:
Console.WriteLine("Unknown day");
break;
}
```
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number (1-7): ");
int dayNumber = int.Parse(Console.ReadLine());
string day;
switch (dayNumber)
{
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
case 7:
day = "Sunday";
break;
default:
day = "Invalid input";
break;
}
6. Jump Statements:
- C# provides jump statements like `break`, `continue`, and `return` that can be
used within loops and methods to control the flow of execution.
In C#, jump statements are used to control the flow of a program by transferring
control to a different part of the code. C# provides several jump statements,
including `break`, `continue`, `return`, `goto`, and `throw`. Here's an explanation
of each jump statement:
1. `break` Statement:
- The `break` statement is primarily used within loops (`for`, `while`, `do-
while`) and `switch` statements to exit the loop or switch block prematurely.
- It is often used when a specific condition is met, and you want to exit the loop
or switch statement early.
2. `continue` Statement:
- The `continue` statement is used within loops to skip the current iteration and
move to the next one.
- It is often used when a specific condition is met, and you want to skip some
processing for the current iteration.
3. `return` Statement:
- The `return` statement is used to exit a method and return a value (if the
method has a return type).
- It can also be used to exit a method without returning a value (in a method
with a `void` return type).
Example:
```csharp
int Add(int a, int b)
{
return a + b; // Exits the method and returns the sum of a and b
}
```
4. `goto` Statement:
- The `goto` statement allows you to transfer control to a labeled statement in
your code.
- It is generally considered a less desirable way to control program flow and
should be used sparingly.
Example:
```csharp
int x = 0;
start:
if (x < 5)
{
Console.WriteLine("x: " + x);
x++;
goto start; // Jumps back to the 'start' label
}
```
5. `throw` Statement:
- The `throw` statement is used to throw an exception in C#. It transfers control
to the nearest catch block that can handle the exception.
Example:
```csharp
if (someCondition)
{
throw new Exception("An error occurred."); // Throws an exception
}
```
While these jump statements provide control over program flow, it's important to
use them judiciously to ensure your code remains readable and maintainable. In
many cases, there are alternative control flow structures, such as `if-else` and
`switch`, that can make your code more understandable.
Certainly! Here are some C# programs that demonstrate the use of jump
statements: `break`, `continue`, `return`, `goto`, and `throw`.
**1. `break` Statement Program:**
```csharp
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break; // Exits the loop when i is 5
}
Console.WriteLine("Iteration: " + i);
}
}
}
```
In this program, the `break` statement is used to exit the `for` loop when `i` is
equal to 5.
```csharp
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
if (i % 2 == 0)
{
continue; // Skips even numbers
}
Console.WriteLine("Odd Number: " + i);
}
}
}
```
In this program, the `continue` statement is used to skip even numbers in the `for`
loop.
```csharp
using System;
class Program
{
static void Main()
{
int result = Add(3, 4);
Console.WriteLine("Result: " + result);
}
In this program, the `return` statement is used to exit the `Add` method and return
the sum of two numbers.
```csharp
using System;
class Program
{
static void Main()
{
int x = 0;
start:
if (x < 5)
{
Console.WriteLine("x: " + x);
x++;
goto start; // Jumps back to the 'start' label
}
}
}
```
```csharp
using System;
class Program
{
static void Main()
{
try
{
int result = Divide(10, 0);
Console.WriteLine("Result: " + result);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
These programs demonstrate how to use jump statements to control program flow
and handle various scenarios in C# code.
Methods:
In C#, methods are blocks of code that can be defined to perform a specific task
or operation. Methods are a fundamental building block of C# programs, and they
provide modularity and code organization. Here's an overview of methods in C#:
Calling Methods:
You can call a method by using its name followed by parentheses `()`:
Return Statements:
Methods can return values using the `return` statement. The type of the returned
value must match the method's declared return type. For methods with no return
value, you use `void`.
```csharp
public int Multiply(int a, int b)
{
return a * b;
}
Method Overloading:
C# allows you to define multiple methods with the same name but different
parameter lists. This is known as method overloading.
```csharp
public int Add(int a, int b)
{
return a + b;
}
public double Add(double a, double b)
{
return a + b;
}
using System;
class Program
{
static void Main()
{
double circleArea = CalculateArea(5.0);
Console.WriteLine($"Area of Circle: {circleArea}");
Modifiers:
- `static`: Indicates that the method belongs to the type itself, rather than an
instance of the type.
- `public`, `private`, `protected`, `internal`: Control the accessibility of the
method.
- `virtual`, `override`, `sealed`, `abstract`: Used in object-oriented programming to
define method behavior in inheritance scenarios.
Optional Parameters:
C# allows you to specify default values for parameters, making them optional.
```csharp
public void DisplayInfo(string name, int age = 25)
{
Console.WriteLine($"Name: {name}, Age: {age}");
}
```
Method Signature:
A method's signature includes its name and parameter list. It does not include the
return type. Method overloading is based on the method signature.
```csharp
public int Add(int a, int b); // Method signature: Add(int, int)
public double Add(double a, double b); // Method signature: Add(double, double)
```
Methods are essential for structuring your code, improving code reusability, and
encapsulating logic. They allow you to break down complex tasks into smaller,
manageable pieces.
using System;
class Program
{
static void Main()
{
int num1 = 10;
int num2 = 5;
In C#, the `foreach` loop is used for iterating through the elements of a collection
or an array without the need to manually manage indices or counters. It simplifies
the process of iterating through a collection, making your code more concise and
readable.
```csharp
using System;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
In this example:
- We use a `foreach` loop to iterate through each element in the `numbers` array.
The loop assigns each element to the variable `number` during each iteration.
The `foreach` loop is particularly useful when you need to iterate through
elements sequentially in a collection, such as arrays, lists, or any other type that
implements the `IEnumerable` interface. It automatically handles the iteration and
does not require manual index management, which makes your code more robust
and less error-prone.
C# Array Statements:
In C#, arrays are used to store collections of elements of the same data type in
a contiguous block of memory. Arrays are essential for managing and
processing data efficiently. Here's an overview of C# arrays, including
declaration, initialization, and common array operations:
1. Declaring Arrays:
To declare an array in C#, you specify the data type of the elements followed
by square brackets `[]` and then provide a name for the array variable.
dataType[] arrayName;
```
For example:
2. Initializing Arrays:
Arrays can be initialized when declared or later using the `new` keyword. You
also need to specify the size (length) of the array.
You can initialize an array with values when declaring it using an array
initializer or assign values to individual elements later.
Array elements are accessed using an index, which starts at 0 for the first
element. You can use square brackets `[]` to specify the index.
int[] numbers = { 1, 2, 3, 4, 5 };
int firstNumber = numbers[0]; // Accesses the first element (1)
int thirdNumber = numbers[2]; // Accesses the third element (3)
```
5. Array Length:
You can obtain the length (number of elements) of an array using the `Length`
property.
int[] numbers = { 1, 2, 3, 4, 5 };
int length = numbers.Length; // Gets the length of the array (5)
```
You can use loops, such as `for` or `foreach`, to iterate through the elements of
an array.
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
```
7. Multidimensional Arrays:
int[,] matrix = new int[3, 2]; // 2D integer array with 3 rows and 2 columns
int[][] jaggedArray = new int[3][]; // Jagged array with 3 rows (arrays of
varying lengths)
```
Arrays are a fundamental data structure in C#, and they are used in various
scenarios for data storage, processing, and manipulation. Understanding arrays
is crucial for many programming tasks.
class Program
{
static void Main()
{
// Initialize an integer array with values
int[] numbers = { 1, 2, 3, 4, 5 };
```csharp
using System;
class Program
{
static void Main()
{
// Initialize a string array with names
string[] names = { "Alice", "Bob", "Charlie" };
```csharp
using System;
class Program
{
static void Main()
{
// Initialize an integer array
int[] numbers = { 10, 20, 30, 40, 50 };
```csharp
using System;
class Program
{
static void Main()
{
// Initialize an integer array
int[] numbers = { 10, 20, 30, 40, 50 };
int target = 30;
if (found)
{
Console.WriteLine($"{target} found in the array.");
}
else
{
Console.WriteLine($"{target} not found in the array.");
}
}
}
```
These programs illustrate how to declare, initialize, access elements, and perform
basic operations on arrays in C#. You can modify and expand these examples to
suit your specific needs.
C# Statements Strings:
In C#, strings are used to represent and manipulate text data. Strings are
sequences of characters enclosed in double quotes (`"`). C# provides a rich set of
features and methods for working with strings. Here's an overview of common
string operations and examples:
```csharp
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
```
```csharp
int age = 30;
string message = $"My name is {fullName} and I am {age} years old.";
```
```csharp
string greeting = "Hello, ";
string name = "Alice";
string welcomeMessage = greeting + name;
```
You can get the length (number of characters) of a string using the `Length`
property:
```csharp
string text = "Hello, World!";
int length = text.Length; // Gets the length of the string (12)
```
```csharp
char firstChar = text[0]; // Gets the first character ('H')
char fifthChar = text[4]; // Gets the fifth character ('o')
```
**6. Substrings:**
```csharp
string subString = text.Substring(0, 5); // Extracts "Hello"
```
You can compare strings using methods like `Equals`, `Compare`, and operators
like `==` and `!=`.
```csharp
bool isEqual = text.Equals("Hello, World!");
bool areEqual = text == "Hello, World!";
```
You can search for substrings within a string using methods like `Contains`,
`IndexOf`, and `LastIndexOf`.
```csharp
bool containsWorld = text.Contains("World");
int indexOfComma = text.IndexOf(",");
int lastIndex = text.LastIndexOf("o");
```
You can split a string into an array of substrings using the `Split` method:
```csharp
string csvData = "John,Doe,30";
string[] parts = csvData.Split(',');
```
```csharp
string upperCaseText = text.ToUpper();
string lowerCaseText = text.ToLower();
string replacedText = text.Replace("Hello", "Hi");
string trimmedText = text.Trim();
```
These are some of the common operations and methods for working with strings
in C#. Strings are integral to many C# applications, and understanding how to
manipulate and work with them is essential for text processing and formatting
tasks.
using System;
class Program
{
static void Main()
{
// Declare and initialize strings
string firstName = "John";
string lastName = "Doe";
// Concatenate strings
string fullName = firstName + " " + lastName;
Console.WriteLine("Full Name: {fullName}"+fullName);
// String interpolation
int age = 30;
string message = "My name is {fullName} and I am {age} years old.";
Console.WriteLine(message);
// String length
string text = "Hello, World!";
int length = text.Length;
Console.WriteLine("Length of the string: {length}"+length);
// Substring extraction
string subString = text.Substring(0, 5);
Console.WriteLine("Substring: {subString}"+subString);
// String comparison
bool isEqual = text.Equals("Hello, World!");
bool areEqual = text == "Hello, World!";
Console.WriteLine("Are equal (using Equals): {isEqual}");
Console.WriteLine("Are equal (using ==): {areEqual}");
// String searching
bool containsWorld = text.Contains("World");
int indexOfComma = text.IndexOf(",");
int lastIndex = text.LastIndexOf("o");
Console.WriteLine("Contains 'World': {containsWorld}"+containsWorld);
Console.WriteLine("Index of ',': {indexOfComma}"+indexOfComma);
Console.WriteLine("Last index of 'o': {lastIndex}"+lastIndex);
// String splitting
string csvData = "John,Doe,30";
string[] parts = csvData.Split(',');
Console.WriteLine("Splitting CSV data:");
foreach (string part in parts)
{
Console.WriteLine(part);
}
// String manipulation
string upperCaseText = text.ToUpper();
string lowerCaseText = text.ToLower();
string replacedText = text.Replace("Hello", "Hi");
string trimmedText = text.Trim();
Console.WriteLine("Uppercase: {upperCaseText}"+upperCaseText);
Console.WriteLine("Lowercase: {lowerCaseText}"+lowerCaseText);
Console.WriteLine("Replaced: {replacedText}"+replacedText);
Console.WriteLine("Trimmed: {trimmedText}"+trimmedText);
}
}
Structures:
Certainly! Here's an example of a C# program that uses a custom value type
structure (struct) called `Person` to create and work with person objects:
```csharp
using System;
class Program
{
static void Main()
{
// Create instances of the 'Person' struct
Person person1 = new Person("John", "Doe", 30);
Person person2 = new Person("Alice", "Smith", 25);
Console.WriteLine("\nPerson 2:");
person2.DisplayInfo();
}
}
```
In this program:
- We define a custom struct named `Person`, which has fields for first name, last
name, and age, as well as a constructor for creating `Person` instances and a
method to display person information.
- In the `Main` method, we create two `Person` objects (`person1` and `person2`)
and initialize them with values.
- We then call the `DisplayInfo` method on each `Person` object to display their
information.
Enumeration in C#
In C#, an enumeration (enum) is a user-defined value type that consists of a set of
named integral constants. Enums allow you to define a symbolic representation
for a set of related values, making your code more readable and self-explanatory.
Enums are often used to represent things like days of the week, months, error
codes, or any other set of related constants.
```csharp
enum EnumName
{
EnumValue1,
EnumValue2,
EnumValue3,
// ...
}
```
```csharp
using System;
enum DaysOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
class Program
{
static void Main()
{
// Declare a variable of the 'DaysOfWeek' enum type
DaysOfWeek today = DaysOfWeek.Wednesday;
In this example:
- We declare a variable `today` of the `DaysOfWeek` enum type and assign it the
value `DaysOfWeek.Wednesday`.
Enums are useful for improving code clarity, reducing the risk of using incorrect
numeric values, and making your code more maintainable. They are commonly
used to define sets of related constants in your C# programs.
Enumerations (enums) and structures (structs) are both language constructs in C#,
but they serve very different purposes and have distinct characteristics. Here are
the key differences between enumerations and structures:
1. Purpose:
- **Structure (Struct):** Structs are used to create custom value types that can
have multiple fields (data members) with different data types. Structs are used to
encapsulate a group of related variables into a single unit, and they are typically
used for representing small, lightweight objects.
2. **Data Type**:
3. **Usage**:
- **Enumeration (Enum):** Enums are used when you want to represent a set
of related, named constants. They are often used in scenarios where you need to
limit the choice of values, such as defining days of the week, error codes, or menu
options.
- **Structure (Struct):** Structs are used to define custom value types that
group related fields together. They are often used for creating small, self-
contained data structures that can be passed by value.
4. **Initialization**:
- **Structure (Struct):** Structs are initialized using the `new` keyword, and
you can set the initial values for their fields individually. For example: `MyStruct
myInstance = new MyStruct { Field1 = value1, Field2 = value2 };`.
5. **Memory Allocation**:
- **Structure (Struct):** Structs are value types, and their memory is allocated
on the stack (or as part of another object) when they are used. They can have a
larger memory footprint if they contain multiple fields or larger data types.
In summary, enums are used for defining a set of related named constants,
whereas structs are used for defining custom value types with multiple fields.
They serve different purposes and are used in different contexts within C#
programs.