-5

I get two errors every time that say

1) A field initializer cannot reference the non-static field, method, or property Program.csProcess

2) foreach statement cannot operate on variables of type decimal because decimal does not contain a public definition for GetEnumerator

 {
    Process[] csProcess = Process.GetProcessesByName("notepad");
    static var modules = csProcess.Modules;
    static void Main(string[] args)
    {
        foreach (ProcessModule module in modules)
        {
            if (module.ModuleName == "client.dll")
            {
                // do stuff
            }
Roman
  • 11,966
  • 10
  • 38
  • 47

1 Answers1

2

1) Process[] csProcess is not static. Frankly, modules shouldn't be either.

2) You can't use var outside of a method. Use ProcessModuleCollection instead.

Static variables, methods, etc. are scoped to the application, whereas member (non-static variables, methods, etc.) belong to the instance of the class/struct that you create.

This gives more info on when static variables are instantiated: When do static variables get initialized in C#?

You could refactor your code like this if you wanted to keep those variables global to the application:

public class Program
{
    static Process csProcess;
    static ProcessModuleCollection modules;

    static void Main(string[] args)
    {
        csProcess = Process.GetProcessesByName("notepad").FirstOrDefault();
        if (csProcess == null) { return; } // notepad isn't running
        modules = csProcess.Modules;
        foreach (ProcessModule module in modules)
        {
            if (module.ModuleName == "client.dll")
            {
                // do stuff
            }
        }  
    }
}

The current answer takes the first notepad process it finds, and loops through its modules. If you want to check every notepad process that it finds, you need to remove .First(), change Process to Process[], and loop through: foreach (var process in csProcess) { //code }

But I'd advise learning the difference between static and instance variables ASAP.

Community
  • 1
  • 1
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • 1
    this fixed the errors but made another one. 'Process[]' does not contain a definition for 'modules' and no extension method 'modules' accepting a first argument of type 'Process[]' could be found (are you missing a using directive or an assembly reference?) – Luke McFall Feb 26 '17 at 20:27