Rohit
Rohit

Reputation: 10236

Cannot Initialize type 'int' error

I have a simple code in C#

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

namespace MyProject
{
  public static class Class1
  {
    public static int[] Iparray = new int { 12, 9, 4, 99, 120, 1, 3, 10 };
  }
}

however on (Ctrl+Shift+B) the error displayed is

Cannot initialize type 'int' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

I am using vs 2010 and and .NET framework 4

Thank you All

Upvotes: 2

Views: 2187

Answers (7)

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

Try this:-

public static int[] a = new int[] {12, 9, 4, 99, 120, 1, 3, 10 };

instead of

public static int[] Iparray = new int { 12, 9, 4, 99, 120, 1, 3, 10 };

Upvotes: 1

Alex
Alex

Reputation: 6149

Add [] to your code

public static int[] Iparray = new int[] { 12, 9, 4, 99, 120, 1, 3, 10 };

Upvotes: 1

backtrack
backtrack

Reputation: 8144

int[] values = new int[] { 1, 2, 3 };
or this:

int[] values = new int[3];
values[0] = 1;
values[1] = 2;
values[2] = 3;

and have a look on this http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98750

You just missed square brackets;

namespace MyProject
{
  public static class Class1
  {
    public static int[] Iparray = new int[] { 12, 9, 4, 99, 120, 1, 3, 10 };
  }
}

Alternative ways of declaring an int array;

  • int[] Iparray = { 12, 9, 4, 99, 120, 1, 3, 10 };

  • int[] Iparray = new[] { 12, 9, 4, 99, 120, 1, 3, 10 };

Upvotes: 1

cuongle
cuongle

Reputation: 75306

You have three ways to define an int array:

 public static int[] Iparray = { 12, 9, 4, 99, 120, 1, 3, 10 };

 public static int[] Iparray = new[] { 12, 9, 4, 99, 120, 1, 3, 10 };
 public static int[] Iparray = new int[] { 12, 9, 4, 99, 120, 1, 3, 10 };

Upvotes: 3

Sayse
Sayse

Reputation: 43300

new int[] { 12, 9, 4, 99, 120, 1, 3, 10 };

Upvotes: 2

Artless
Artless

Reputation: 4568

You're missing brackets. Like this:

int[] a = new int[] { 1, 2, 3 };

Upvotes: 5

Related Questions