1
votes

Apologies if this has been addressed before as I'm new to coding and don't recognize half the code going on.

I'm trying to use a field/variable in the contents of the File.WriteAllText method, but I get an error

CS1020 - An object reference is required for the non static field, method, or property "Program.writePath"

I don't exactly know what this means.

I know that writing the string directly into the method fixes the error, and that there's an automatic fixing tool in my IDE that wants to put argument names "path" and "contents" before each thing (though that doesn't fix it). Why is this the case? How do I use my fields in the method instead of typing them in directly?

Here is the code:

using System;
using System.IO;   

namespace w3consoleapp30_Cs_files
{
    class Program
    {
        public string writePath = "filename.txt";
        public string writeText = "Hello, World!";     

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            File.WriteAllText(writePath, writeText);
        }
    }
}
1
Change public string writePath to public const string writePath. Ditto for writeText. Also, consider using named-parameters in the call to WriteAllText as both parameters are typed as String.Dai
You are accessing the Class level variables in Static method. Please make variables const as @dai suggested, or make your variables static.Umesh CHILAKA
Further note: since you haven't specified a path, you're writing to the application's startup path (at this time, at least). When you deploy, you may not have access rights to write to that path (not a surprise). Consider writing to the User's AppData folder or the common app data path (ProgramData)Jimi

1 Answers

0
votes

C# (like all languages) has specific rules about what parts of a program are allowed to interact with other parts of the program. There are reasons for these rules that you will learn as you keep coding. The compiler is telling you that you broke the rule, so this isn't a valid program.

In c#, when something is static, it means that there is only one of those things in the whole program. C# has a special rule that the main function must always be static, so that it can make sure there can only be one way for your program to start.

The rule that your code breaks is you are trying to use fields that are non-static from a static function. Main is static, so it can't see writePath or writeText because they are not. Main doesn't know which writePath or writeText to use. There are different ways to fix this, but the easiest for now is to add the static keyword at the start of the lines where you set writePath and writeText. This means that there is only one main method, and there is only one writePath and one writeText in your Program class.

An alternative would be to say they are const (constant) which means that there can only be one of them, but that they also cannot ever be changed.