Reputation: 61515
I am creating a really basic program, that has a method to fill an array but I am getting an error I don't understand. I am a Java programmer trying to acclimate to C# and .NET. Any help would be great.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace TestThreads
{
class Program
{
static void Main(string[] args)
{
int[] empty = new int[50001];
int[] filled = new int[50001];
filled = compute(empty); //error occurs here
Console.ReadLine();
}
public int[] compute(int[] inArray)
{
for (int i = 0; i < inArray.Length; i++)
{
inArray[i] = i << 2;
}
return inArray;
}
}
}
Error Message:
Error 1 An object reference is required for the non-static field, method, or property 'TestThreads.Program.compute(int[])' C:\Users\hunter.mcmillen\Desktop\TestProcessSplitting\TestProcessSplitting\Program.cs 17 22 TestThreads
Thanks, Hunter
Upvotes: 1
Views: 201
Reputation: 32505
You're method is not static, but is being referenced from a static method. Change it to static. Solved.
public static int[] compute(int[] inArray) { ... }
Upvotes: 0
Reputation: 1062502
Main
is a static method - it is not specific to any single object - indeed, no instance of Program
is created to call Main
. compute
is an instance method, and needs to be invoked on a single object.
Two options:
make compute
static, which makes sense since it uses no state (fields):
public static int[] compute(int[] inArray) {...}
create an instance in Main
:
var obj = new Program();
filled = obj.compute(empty);
The first is more appealing here. I've included the second purely for completeness.
Upvotes: 2
Reputation: 9627
Add static to the compute method declaration.
public static int[] compute(int[] inArray)
Upvotes: 0
Reputation: 754525
You're trying to call compute
which is an instance method from Main
which is a static
method. To fix this make compute
static as well`
public static int[] compute(int[] inArray)
Upvotes: 6
Reputation: 108937
Change public int[] compute(int[] inArray){...}
to
public static int[] compute(int[] inArray){..}
or change your call from
filled = compute(empty);
to
filled = new Program().compute(empty);
The compute()
method that you have is an instance (non-static) method and requires an instance to be invoked.
Upvotes: 1
Reputation: 6726
The compute method should be static.
public static int[] compute(int[] inArray)
Upvotes: 6