How to returns the default value on out-of-range in C#

2 Answers

0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 7, 13, 9000 };

            int a = arr.ElementAtOrDefault(0);
            int b = arr.ElementAtOrDefault(-1);

            Console.WriteLine(a);
            Console.WriteLine(b);
        }
    }
}


/*
run:
     
7
0
 
*/

 



answered Feb 21, 2017 by avibootz
0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = { "c#", "c", "c++", "java" };


            string a = arr.ElementAtOrDefault(0);
            string b = arr.ElementAtOrDefault(-1);

            Console.WriteLine(a);
            Console.WriteLine(b);
        }
    }
}


/*
run:
     
c#
 
*/

 



answered Feb 21, 2017 by avibootz

Related questions

...