Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Creating an object using new but not assigning it. Good idea/bad idea?

Tags:

c#

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. :)

like image 571
Monali Avatar asked Dec 31 '25 11:12

Monali


1 Answers

It's not bad programming practice if that is what you are asking about. If you have no reason to keep around the reference to the newly created object after that line, then it's perfectly fine.

like image 105
Tejs Avatar answered Jan 02 '26 00:01

Tejs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!