What is valuetuple in c# with example
In C#, a ValueTuple is a lightweight data structure introduced in C# 7.0 that allows you to create tuples with named or unnamed elements. ValueTuples are value types, which means they are structs rather than reference types (classes), making them more memory-efficient. Here's an example of using ValueTuples:
```csharp
using System;
class Program
{
static void Main()
{
// Creating a ValueTuple with named elements
var person = (Name: "John", Age: 30);
// Accessing elements using names
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
// Creating a ValueTuple with unnamed elements
var point = (3, 4);
// Accessing elements using itemN notation
Console.WriteLine($"X: {point.Item1}, Y: {point.Item2}");
}
}
```
In the example above, we create two ValueTuples. The first one has named elements (Name and Age), and the second one has unnamed elements. You can access the elements of a ValueTuple using either their names or the `ItemN` notation, where N is the 1-based index of the element. ValueTuples are useful when you need to group related data together without creating custom classes or structures.
Comments
Post a Comment