When i Compiled the following both codes it gives same result (I think so).
//ManagementObject :
SelectQuery query = new SelectQuery("Win32_Environment");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
Console.WriteLine("Variable : {0}, Value = {1}",envVar["Name"], envVar["VariableValue"]);
//ManagementBaseObject :
SelectQuery query = new SelectQuery("Win32_Environment");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementBaseObject envVar in searcher.Get())
Console.WriteLine("Variable : {0}, Value = {1}",envVar["Name"], envVar["VariableValue"]);
what is the difference between both code execution…?
In this particular case, there is no difference.
The
ManagementObjectSearcher.Get()method returns aManagementObjectCollectionwhich is a collection ofManagementBaseObject. This means that the collection can contain instances of typeManagementBaseObjector of any type that is descended fromManagementBaseObject.However, the
ManagementBaseObjectis designed as a base class, which means that in reality, it won’t be instantiated, but instead, it’s descended classes will be instantiated. Note that this is a just a convention, and it is not enforced by the language or framework.Additionally, since the only class in the framework that (directly) inherits the
ManagementBaseObjectisManagementObject, theGet()effectively returns a collection ofManagementObjectinstances. Note that this is just the current situation, and nothing prevents the creation of additionalManagementBaseObjectinheritors.So, with all mentioned caveats, that means, that if you use only properties defined in the base class (and not overriden) you could iterate either way, and the code will behave exactly the same. In your code you use only the indexer, which is indeed defined, and not overriden, in the
ManagementBaseObjectclass.If you want an example of code that will fail for one loop, and work in the other, you could try any of the properties defined on
ManagementObject, like, for example, Path: