Passing Parameters by Reference in C#
The ref modifier enables methods to operate directly on variables passed as arguments. Any modifications within the method persist in the original variable scope.
void IncrementNumber(ref int input)
{
input *= 2;
}
int counter = 25;
IncrementNumber(ref counter);
Console.WriteLine(counter); // Displays 50
Extracting String Segments
The Substring function retrieves portions of a string based on index positions and length parameters.
string fullText = "Programming in C#";
string segment = fullText.Substring(0, 11);
Console.WriteLine(segment); // Outputs "Programming"
Runtime Type Inspection with Reflection
Reflection provides mechanisms to examine and manipulate type information dynamically during program execution.
Type employeeType = typeof(Employee);
var instance = (Employee)Activator.CreateInstance(employeeType);
MethodInfo method = employeeType.GetMethod("ProcessData");
method.Invoke(instance, new object[] { "sample" });
String Parsing with Split Method
The Split operation divides a string into multiple substrings based on specified delimiter characters.
string rawData = "product:quantity:price";
string[] components = rawData.Split(':');
foreach (var part in components)
{
Console.WriteLine(part);
}
Implementing WebSocket Connections
WebSocket functionality in C# facilitates persistent, bidirectional communication channels over TCP connections.
using var client = new ClientWebSocket();
await client.ConnectAsync(new Uri("wss://api.example.com/socket"), CancellationToken.None);
var message = Encoding.UTF8.GetBytes("Initialize connection");
await client.SendAsync(new ArraySegment<byte>(message), WebSocketMessageType.Text, true, CancellationToken.None);
var buffer = new byte[2048];
var response = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, response.Count));
Managing Data with DataTable
DataTable offers an in-memory representation of tabular data with schema definition and row manipulation capabilities.
var inventoryTable = new DataTable();
inventoryTable.Columns.Add("ProductID", typeof(int));
inventoryTable.Columns.Add("ProductName", typeof(string));
inventoryTable.Columns.Add("InStock", typeof(bool));
inventoryTable.Rows.Add(101, "Laptop", true);
inventoryTable.Rows.Add(102, "Mouse", false);
foreach (DataRow entry in inventoryTable.Rows)
{
Console.WriteLine($"{entry["ProductID"]}: {entry["ProductName"]} - Available: {entry["InStock"]}");
}