I am new to C# and I'm trying to write my first code using var type
.
as you see below ,I make a array of integers
(arr1
) then I tried to make a new var type
and refer my previous array (arr1
--> int[]
) to it . but it occurs some errors that say :
Error CS0236 A field initializer cannot reference the non-static field, method, or property.
is there any helps or hints ?
using System;
class VarType
{
int[] arr1 = { 1, 2, 3 };
var varType = arr1;
}
thanks to helpful comment from Charlieface , I change my code to below it solves another error about another things , but the above error still remains ! what should I do about it ?
using System;
class VarType
{
int[] arr1 = { 1, 2, 3 };
public static void Main()
{
var varType = arr1;
}
}
First up, var
is not a type. It's a special keyword that tells the compiler to infer the type from the data.
So, the two following are equivalent ways of defining an array:
int[] arr1 = { 1, 2, 3 };
var arr2 = { 1, 2, 3 };
Both arr1
and arr2
are int[]
in this example.
The issue with your code is that you're trying to define a field in the class VarType
using the var
keyword which cannot be used for a field.
Had you written it this way it would work:
class VarType
{
void SomeMethod()
{
int[] arr1 = { 1, 2, 3 };
var varType = arr1;
}
}
The second example in your question failed because Main
was declared static
, but the array wasn't. It works if you do this:
class VarType
{
static int[] arr1 = { 1, 2, 3 };
public static void Main()
{
var varType = arr1;
}
}
Or like this:
class VarType
{
int[] arr1 = { 1, 2, 3 };
public void SomeMethod()
{
var varType = arr1;
}
}