I was wondering if it is a good idea to create an object using the new operator but not assign the returned object to any variable. Essentially I am just calling the methods in the same line. For eg:
new Object().ToString();
Well I know the above line won’t do anything but it is just an example. And here is what my real code line looks like (its selenium specific – that is why I gave the above example)
new SelectElement(driver.FindElement(By.Id("fUserCountryID"))).SelectByText("United States");
What it does in plain english: Find an HTML element on the form with ID=fUserCountryID and select the option with value=United States
The compiler allows me to do this and it works fine, but is it a good programming practice?
Please share your expert comments for I am just a beginner. 🙂
You should be judicious in your usage of this, but I don’t see a problem with your above code.
A couple of things I always like to ask myself —
Just be careful with some objects, for example, that may implement
IDisposable. It is a best practice to wrap those in ausing { ... }block so that their resources are cleaned up explicitly.