Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return from a method more than one variable?

Tags:

c#

.net

winforms

This method returns only the process filename:

public static string GetProcessInfo(IntPtr hwnd)
{
    uint pid = 0;
    GetWindowThreadProcessId(hwnd, out pid);
    Process proc = Process.GetProcessById((int)pid);
    return proc.MainModule.FileName.ToString();
}

But I want to return also the process name:

proc.ProcessName;
like image 867
Manuel Spechia Avatar asked Nov 30 '22 00:11

Manuel Spechia


1 Answers

I believe you have four options (in preference order)

  • Return proc.MainModule directly and extract necessary information from caller.
public static ProcessModule GetProcessInfo(IntPtr hwnd)
{
    uint pid = 0;
    GetWindowThreadProcessId(hwnd, out pid);
    Process proc = Process.GetProcessById((int)pid);
    return proc.MainModule;
}
  • Create a class containing both values and return that
public class ProcessInformation
{
    public string FileName;
    public string ProcessName;
}

public static ProcessInformation GetProcessInfo(IntPtr hwnd)
{
    uint pid = 0;
    GetWindowThreadProcessId(hwnd, out pid);
    Process proc = Process.GetProcessById((int)pid);
    var pi = new ProcessInformation 
    {  
        proc.MainModule.FileName,
        proc.MainModule.ProcessName
    }
    return pi;
}
  • Return a tuple from method Tuple<string, string>
public static Tuple<string, string> GetProcessInfo(IntPtr hwnd)
{
    uint pid = 0;
    GetWindowThreadProcessId(hwnd, out pid);
    Process proc = Process.GetProcessById((int)pid);
    return return Tuple.Create(proc.MainModule.FileName,proc.MainModule.ProcessName);
}
  • Create 2 out parameters on your method (I never seen two out parameters implemented and I discourage this since definitively smells, but it's an option C# provides)
string GetProcessInfo(IntPtr hwnd, out fileName, out processName)
like image 150
Claudio Redi Avatar answered Dec 10 '22 07:12

Claudio Redi