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);
}
}
}
>Solution :
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, because someone could make their own copy of Program and it would have its own version of those fields that are different.
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.