Search code examples
c#.netconsoleruntime-error

error CS0120: An object reference is required for the non-static field, method, or property 'Encoding.GetBytes(string)'


I'm making a console app using .NET and when I ran the program I got this error. error CS0120: An object reference is required for the non-static field, method, or property Encoding.GetBytes(string). It says the error came from this line: content.Add(Encoding.GetBytes("\n"+str)); (content is a List of type string and str is a string)


Solution

  • In Encoding.GetBytes Method documentation:

    public virtual byte[] GetBytes (char[] chars);

    It is not a static method, thus you are not allowed direct calling Encoding.GetBytes method.

    Instead, you need to declare and assign an Encoding variable; only then use this variable to call GetBytes method.

    var str = "Happy ending"; // Sample data
    var encoding = Encoding.UTF8; // Set to your desired encoding
    var bytes = encoding.GetBytes("\n"+str); // Return type: byte[]
    

    For adding bytes into content of List, you may convert your bytes to desired format first.

    [Not .ToString(), it will returns result: "System.Byte[]"]

    var byteString = String.Join(" ", bytes);  // Format to your desired format
    // Result of byteString: 10 72 97 112 112 121 32 101 110 100 105 110 103
    content.Add(byteString);