1

So I am looking at the following example (http://zetcode.com/lang/csharp/arrays/), titled "c# array slices". When I copy and paste the following example in Microsoft Visual Studio:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

    namespace s_Sandbox
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] array = new int[] { 1, 2, 3, 4, 5 };
                array[1..2];
            }
        }
    }

There is a red underline under [1..2] and I get a Syntax error, "," expected ... why is this? What am I missing?

datainc
  • 45
  • 6
  • https://stackoverflow.com/questions/406485/array-slices-in-c-sharp/55498674#55498674 – Steve Aug 05 '20 at 15:01
  • 1
    this is supported starting with c# 8 – Homungus Aug 05 '20 at 15:02
  • @Steve that does not answer why I am getting the error; rather an alternate solution. – datainc Aug 05 '20 at 15:03
  • @Homungus I have viewed the property settings for my solution, I am using .NET Framework 4.5.2... that shouldn't be an issue though? – datainc Aug 05 '20 at 15:04
  • 1
    look here how to use c# 8.0 with asp.net project: https://stackoverflow.com/questions/56651472/does-c-sharp-8-support-the-net-framework – Homungus Aug 05 '20 at 15:06
  • Even if you enable C# 8, you still can't use the `range` operator when building for the .Net Framework 4.x. [unless you take some additional steps](https://www.meziantou.net/how-to-use-csharp-8-indices-and-ranges-in-dotnet-standard-2-0-and-dotn.htm). – Matthew Watson Aug 05 '20 at 15:15

1 Answers1

3

That is because the range operator [n..m] is available for version C# 8.0 or greater

This might be useful too

Target framework    version C# language version default
.NET Core   3.x C# 8.0
.NET Core   2.x C# 7.3
.NET Standard   2.1 C# 8.0
.NET Standard   2.0 C# 7.3
.NET Standard   1.x C# 7.3
.NET Framework  all C# 7.3

If upgrading is not an option you can use:

      int[] array = { 1, 2, 3, 4, 5 };
      var t = array.Take(2);
Alex Leo
  • 2,781
  • 2
  • 13
  • 29