C# Error 01: An object reference is required for the non-static field, method, or property in C# ?
The CS0120 error occurs because you're trying to call a non-static method from a static context without an instance of the class.
📌 Solution
Since Main()
is static
, all methods you call from it must also be static, or you need to create an instance of the class.
✅ Corrected Code (Make Method Static)
If your method does not depend on instance variables, declare it as static
:
using System;
using System.IO;
class Program
{
static void Main()
{
// Get application running path
string appPath = AppDomain.CurrentDomain.BaseDirectory;
string logDirectory = Path.Combine(appPath, "Output", "Log");
// Ensure log directory exists
Directory.CreateDirectory(logDirectory);
// Define log file path
string logFilePath = Path.Combine(logDirectory, "app.log");
// ✅ Call static method without instance
WriteLog(logFilePath, "Application started.");
WriteLog(logFilePath, "Processing data...");
WriteLog(logFilePath, "Application finished successfully.");
Console.WriteLine($"Logs written to: {logFilePath}");
}
/// <summary>
/// ✅ Make this method static to call from Main()
/// </summary>
static void WriteLog(string filePath, string message)
{
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} | {message}";
File.AppendAllText(filePath, logEntry + Environment.NewLine);
}
}
🛑 If You Cannot Make WriteLog()
Static
Then, you need to create an instance of Program
in Main()
:
class Program
{
static void Main()
{
Program p = new Program(); // ✅ Create instance
p.WriteLog("log.txt", "Hello, log!");
}
void WriteLog(string filePath, string message)
{
File.AppendAllText(filePath, $"{DateTime.Now} | {message}\n");
}
}
🚀 Best Practice: Use a Dedicated Logger Class
For better organization, move logging to a separate Logger
class:
class Logger
{
public static void WriteLog(string filePath, string message)
{
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} | {message}";
File.AppendAllText(filePath, logEntry + Environment.NewLine);
}
}
Then call:
Logger.WriteLog("log.txt", "Application started.");
If you like comment and share. 🚀
0 Comments