Huron_rare Huron_rare - 1 month ago 15
C# Question

What's the difference between Process[] and Process()[]

I was doing research for my pattern scanner but I came to this problem.

The pattern scanner that I saw needed a handler of the process but the way I'm doing it

Process[] P = Process.GetProcessesByName("pName");


doesn't have
P.Handle
and I went to msdn but there it says it have. But why mine doesn't?

What is the difference between those two lines of code?

Process P = Process.GetProcessesByName("pName")[0];
Process[] P = Process.GetProcessesByName("pName");

Answer Source

This gets the first process that has a name of "pName":

Process P = Process.GetProcessesByName("pName")[0];

Note that this will cause an "index out of bounds" exception if there aren't any.

This gets a list (or an array, actually) of all processes that have a name of "pName":

Process[] P = Process.GetProcessesByName("pName");

Note that this won't cause an exception if there aren't any; it'll just return an empty array.

With the latter, you can index it just like the former, if you want the first match:

Process[] P = Process.GetProcessesByName("pName");
if (P.Length > 0)
{
    Process process = P[0];  //Get the first one
}
else
{
    Log("No such process!");
}

Or (the way I would do it) use LINQ:

Process p = Process.GetProcessesByName("pName").FirstOrDefault();
if (p != null) 
{
    //Do something with the process
}