Questions :
- How do you implement events in C#?
- What are lambda expressions?
- Explain the use of LINQ in C#.
- What is a lambda expression?
- How do you create a thread in C#?
Implementing Events in C#:
Events in C# are implemented using delegates. Here's how you can declare and raise events in a class:
using System; public class Button { public event EventHandler Click; // Declare the event public void OnClick() // Method to raise the event { Click?.Invoke(this, EventArgs.Empty); } }
In this example, the Click
event is declared as an instance of the EventHandler
delegate. The OnClick
method raises the event by invoking the delegate with appropriate arguments.
Lambda Expressions:
Lambda expressions in C# are concise syntax for defining anonymous methods or functions. They allow you to write inline code blocks as arguments to methods or to define delegates or expression trees more compactly.
Func<int, int, int> add = (x, y) => x + y; // Lambda expression defining addition Console.WriteLine(add(2, 3)); // Output: 5
Here, the lambda expression (x, y) => x + y
defines an anonymous function that takes two integers x
and y
as parameters and returns their sum.
LINQ (Language Integrated Query) in C#:
LINQ is a powerful feature in C# that provides a uniform way to query data from various data sources such as collections, arrays, databases, XML, and more. It allows developers to write queries using a SQL-like syntax directly within C# code.
var numbers = new int[] { 1, 2, 3, 4, 5 }; var evenNumbers = numbers.Where(n => n % 2 == 0); // LINQ query to filter even numbers foreach (var number in evenNumbers) { Console.WriteLine(number); // Output: 2 4 }
In this example, LINQ's Where
method is used to filter even numbers from the numbers
array based on a lambda expression.
Lambda Expression:
A lambda expression in C# is an anonymous function that can contain expressions and statements. It provides a concise syntax for defining inline functions without having to explicitly declare a separate method.
Func<int, int, int> add = (x, y) => x + y; // Lambda expression defining addition Console.WriteLine(add(2, 3)); // Output: 5
Here, (x, y) => x + y
is a lambda expression that defines an anonymous function taking two integers x
and y
as parameters and returning their sum.
Creating a Thread in C#:
You can create a thread in C# using the Thread
class from the System.Threading
namespace. Here's an example:
using System.Threading; public class Program { public static void Main() { Thread thread = new Thread(MyThreadMethod); thread.Start(); } public static void MyThreadMethod() { // Thread logic goes here Console.WriteLine("Thread is running..."); } }In this example, a new thread is created using the
Thread
class, and its Start
method is called to begin execution of the MyThreadMethod
.
Comments
Post a Comment