I'm wondering if there's a better way to implement the following code from a maintainability and a memory impact standpoint. Looking at the following code would it be better to use properties? I see a lot of repeat code and I'm wondering what the best way to go about this would be.
public class Win32OperatingSystem
{
internal ulong BytesToMegaBytes(ulong bytes)
{
return bytes / (ulong)1024;
}
public ulong FreePhysicalMemory()
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT FreePhysicalMemory FROM Win32_OperatingSystem");
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext()) return 0;
return BytesToMegaBytes((ulong)enu.Current["FreePhysicalMemory"]);
}
}
public ulong TotalVirtualMemorySize()
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT TotalVirtualMemorySize FROM Win32_OperatingSystem");
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext()) return 0;
return BytesToMegaBytes((ulong)enu.Current["TotalVirtualMemorySize"]);
}
}
public ulong FreeVirtualMemory()
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT FreeVirtualMemory FROM Win32_OperatingSystem");
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext()) return 0;
return BytesToMegaBytes((ulong)enu.Current["FreeVirtualMemory"]);
}
}
}
Rather than repeat the method would it be better to do something like...
MyMethod(string propertyName)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM Win32_OperatingSystem");
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext()) return 0;
return BytesToMegaBytes((ulong)enu.Current[propertyName]);
}
}