0% found this document useful (0 votes)
25 views

C# With Comprehensive Examples

Uploaded by

Lyfe Lerner
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

C# With Comprehensive Examples

Uploaded by

Lyfe Lerner
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

Certainly!

Let's delve into various programming concepts in C# with comprehensive


examples to illustrate each concept:

### 1. **Variables and Data Types:**


```csharp
int age = 30;
double height = 5.9;
string name = "John Doe";
bool isStudent = true;
char grade = 'A';
```
Explanation:
- `int`, `double`, `string`, `bool`, `char`: These are data types in C#
representing integers, floating-point numbers, strings, boolean values, and
characters respectively.
- `age`, `height`, `name`, `isStudent`, `grade`: These are variables of respective
data types.

### 2. **Control Flow:**


```csharp
int score = 85;

if (score >= 90)


{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
```
Explanation:
- `if`, `else if`, `else`: These are conditional statements in C# used to control
the flow of execution based on conditions.
- The code checks the value of `score` and prints the corresponding grade based on
the condition.

### 3. **Methods and Functions:**


```csharp
class Calculator
{
static int Add(int num1, int num2)
{
return num1 + num2;
}

static void Main()


{
int result = Add(5, 3);
Console.WriteLine("Result: " + result);
}
}
```
Explanation:
- `Add(int num1, int num2)`: This method takes two integer parameters and returns
their sum.
- `Main()`: Entry point of the program. Calls the `Add` method and prints the
result.

### 4. **Object-Oriented Programming (OOP):**


```csharp
class Person
{
public string Name;
public int Age;

public void DisplayInfo()


{
Console.WriteLine("Name: " + Name);
Console.WriteLine("Age: " + Age);
}
}

class Program
{
static void Main()
{
Person person1 = new Person();
person1.Name = "John";
person1.Age = 30;
person1.DisplayInfo();
}
}
```
Explanation:
- `Person`: Defines a class with fields (`Name`, `Age`) and a method
(`DisplayInfo`) to display person's information.
- `Main()`: Creates an instance of `Person` class, sets its properties, and calls
`DisplayInfo` method.

### 5. **Arrays and Collections:**


```csharp
int[] numbers = new int[3] { 1, 2, 3 };

foreach (int num in numbers)


{
Console.WriteLine(num);
}
```
Explanation:
- `int[] numbers`: Declares an integer array with three elements.
- `foreach` loop iterates through each element of the array and prints it.

### 6. **Exception Handling:**


```csharp
try
{
int result = Divide(10, 0);
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}

static int Divide(int dividend, int divisor)


{
if (divisor == 0)
{
throw new DivideByZeroException("Cannot divide by zero.");
}
return dividend / divisor;
}
```
Explanation:
- `try-catch` block handles exceptions. If an exception occurs in the `try` block,
it's caught in the `catch` block.
- The `Divide` method throws a `DivideByZeroException` if the divisor is zero.

### 7. **File I/O:**


```csharp
using (StreamWriter writer = new StreamWriter("file.txt"))
{
writer.WriteLine("Hello, World!");
}

string text = File.ReadAllText("file.txt");


Console.WriteLine("File Content: " + text);
```
Explanation:
- `StreamWriter` writes text to a file, and `StreamReader` reads text from a file.
- `File.WriteAllText` writes text to a file, and `File.ReadAllText` reads text from
a file.

### 8. **Delegates and Events:**


```csharp
public delegate void EventHandler(string message);

class Publisher
{
public event EventHandler MessageSent;

public void SendMessage(string message)


{
MessageSent?.Invoke(message);
}
}

class Subscriber
{
public void OnMessageReceived(string message)
{
Console.WriteLine("Received Message: " + message);
}
}

class Program
{
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();

publisher.MessageSent += subscriber.OnMessageReceived;

publisher.SendMessage("Hello from Publisher!");


}
}
```
Explanation:
- `delegate` defines a type that represents a method signature.
- `event` allows classes to provide notifications when something interesting
happens.
- The `Publisher` class publishes messages, and the `Subscriber` class receives and
handles them.

### 9. **Asynchronous Programming:**


```csharp
async Task<int> FetchDataAsync()
{
HttpClient client = new HttpClient();
string data = await client.GetStringAsync("https://api.example.com/data");
return data.Length;
}
```
Explanation:
- `async` keyword allows a method to use `await` keyword.
- `await` keyword pauses the execution of the method until the awaited task
completes asynchronously.

### 10. **LINQ (Language Integrated Query):**


```csharp
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

var evenNumbers = from num in numbers


where num % 2 == 0
select num;

foreach (var num in evenNumbers)


{
Console.WriteLine(num);
}
```
Explanation:
- LINQ provides a uniform way to query data from different sources.
- `from`, `where`, and `select` are LINQ keywords used for querying data.

These examples cover various programming concepts in C#, providing a solid


foundation for building applications. Experiment with them, modify the code, and
explore further to deepen your understanding.

You might also like