c sharp

What is Range in C#

C# Range is a powerful feature that allows you to work with ranges of elements in an array or collection. With this feature, you can easily extract or manipulate specific parts of your data without the need for complicated code. Learning how to use C# Range can help you write more efficient and effective code, regardless of your level of programming experience.

In this article, we will explore the basics of C# Range and how you can use it to improve your programming skills.

What is C# Range

In C#, Range is a pre-defined data type that serves as a representation of a specific range of elements in a sequence or collection. It is not an operator or function but rather a type that developers can use to create a Range object.

The Range object allows developers to select or slice a specific subset of elements from a collection or sequence by defining the start and end positions of the range with two indices. To utilize Range in C#, one needs to create a Range object by specifying the start and end points of the specified range.

Range r = start..end;

Here, start and end are the indices that represent the start and end positions of the range, and the double dots (..) operator is used to create a Range object.

Here is an example code that uses the Range operator in C#. We initiated an array of numbers and then created a Range operator r1 and initialized it. Then we displayed the numbers using the range operator:

using System;

namespace program {

class testrange {

    static void Main(string[] args)
    {
        int[] numbers = new int[] {10, 25, 57, 78, 59,
                            34, 22, 12, 99, 50, 79};
        Range r1 = 0..3;
        var a1 = numbers[r1];
        Console.Write("The List of numbers is: ");
        foreach(var st_1 in a1)
        Console.Write($" {st_1} ");    
    }
   }


}

The above code contains an array of integers named numbers with 11 elements. It then creates a Range object r1 representing the first 3 elements of the array (from index 0 to 2). The code then uses the Range object to extract the corresponding elements from the numbers array and stores them in a variable a1. Finally, the code prints the values in a1 using a foreach loop.

Bottom Line

C# Range is a powerful tool that allows developers to manipulate specific parts of their data without the need for complicated code. By creating a Range object with start and end indices, developers can easily select or slice a subset of elements from a collection or sequence. Understanding how to use C# Range can greatly improve your programming skills and help you write more efficient and effective code.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.