Reputation: 39
noob here. I am trying to write a code to display and open a file path and after much searching and pain I still have not been able to get past the An object reference is required for the non-static field, method, or property (CS0120)
error.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ArrayList = System.Collections.ArrayList;
namespace Risk_Stats
{
public class Risk_stats_CSV_generator
{
string outputPath = Path.GetFileName( Path.GetDirectoryName( @"U:\XXXX" ) );
public static void Main(string[] args)
{
System.Diagnostics.Process.Start(outputpath);
}
}
}
I'm struggling with understanding the available solutions on this error. What does an object reference mean? And how would it be placed in the code?
Upvotes: 0
Views: 558
Reputation: 29668
Your outputPath
needs to be declared static as well.
private static string outputPath = Path.GetFileName( Path.GetDirectoryName( @"U:\XXXX" ) );
public static void Main(string[] args)
{
System.Diagnostics.Process.Start(outputpath);
}
In your original version you're attempting to access a member that's tied to an instance of Risk_stats_CSV_generator
, however static members have no instance to refer to so it's disallowed.
You can mitigate against these kind of errors by changing your class to be static as well, for example:
namespace Risk_Stats
{
public static class Risk_stats_CSV_generator
{
...
}
}
This will prevent you from using non-static members.
Upvotes: 1