1

I want to convert a decimal number (int) to a binary number and print it out. My code in C# is this:

    int t1 = 2;
    public string test = Convert.ToString(t1, 2);

I get the error:

A field initializer cannot reference the nonstatic field, method, or property 'field'

I cannot find a solution for this :/

I found the solution: you have to declare t1 as static. static int t1 works!

Alex
  • 21
  • 1
  • 3
  • 1
    Possible duplicate of [A field initializer cannot reference the nonstatic field, method, or property](https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property) – Magnetron Mar 27 '19 at 11:03
  • 3
    Is this code in a class definition or method body? (it runs fine from a method body if you remove `public`: https://dotnetfiddle.net/N9muSK) – vc 74 Mar 27 '19 at 11:07
  • this code is not in a method so far but I plan to implent it in one. Right now I want to try to it out if it works. – Alex Mar 27 '19 at 11:09
  • You'll save yourself time and effort if you start building the method right now – vc 74 Mar 27 '19 at 11:10

1 Answers1

0

Check this code,

using System;

public class Program
{
    public static void Main()
    {
        int static t1 = 2;
        string test = Convert.ToString(t1, 2);
        Console.WriteLine(test);
    }
}

Thanks.

Kinjal Parmar
  • 342
  • 1
  • 3
  • 17
Akash Limbani
  • 1,283
  • 4
  • 14
  • 34