Open In App

How to check whether the index is from start or end in C#?

Last Updated : 28 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The Index Structure is introduced in C# 8.0. It represents a type that can be used to index a collection or sequence and it can be started from the start or the end. You are allowed to check the given index is from the start or end of the given collection or sequence with the help of IsFromEnd Property provided by the Index struct. If IsFromEnd property returns false, then it means the index is from the start or if the IsFromEnd property returns true, then it means the index is from the end.]

Syntax:

public property bool IsFromEnd { bool get(); };

Example 1:




// C# program to illustrate the
// concept of the IsFromEnd property
using System;
  
namespace example {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
  
        // Creating new indexes
        // Using Index() constructor
        var val1 = new Index(1, true);
        var val2 = new Index(2, true);
        var val3 = new Index(1, false);
        var val4 = new Index(2, false);
  
        // Checking if the specified 
        // index start from the end
        // or not
        var res1 = val1.IsFromEnd;
        var res2 = val2.IsFromEnd;
        var res3 = val3.IsFromEnd;
        var res4 = val4.IsFromEnd;
  
        // Display indexes and their values
        Console.WriteLine("Index:{0} Start from end?: {1}", val1, res1);
        Console.WriteLine("Index:{0} Start from end?: {1}", val2, res2);
        Console.WriteLine("Index:{0} Start from end?: {1}", val3, res3);
        Console.WriteLine("Index:{0} Start from end?: {1}", val4, res4);
    }
}
}


Output:

Index:^1 Start from end?: True
Index:^2 Start from end?: True
Index:1 Start from end?: False
Index:2 Start from end?: False

Example 2:




// C# program to illustrate the
// concept of the IsFromEnd property
using System;
  
namespace example {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
  
        string[] greetings = new string[] {"Hello", "Hola", "Namaste"
                                "Bonjour", "Ohayo", "Ahnyounghaseyo"};
  
        var val1 = new Index(1, true);
  
        // Checking the given index
        // is the end index or not
        if (val1.IsFromEnd == true) {
            Console.WriteLine("The given index is from end "+
                     "and the value is: " + greetings[val1]);
        }
        else {
            Console.WriteLine("The given index is from start and"+
                             " the value is: " + greetings[val1]);
        }
    }
}
}


Output:

The given index is from end and the value is: Ahnyounghaseyo


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads