Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new object in function call

Tags:

c#

I was wondering if it is safe to create new objects as part of a method (or indeed constructor call)

Such as the convuluted example below:

public class Igloo
{
    public int i = 5;
}

public class Program
{
    static void Main(string[] args)
    {
        DoSomething(new Igloo());
    }

    private static void DoSomething(Igloo i)
    {
        Debug.WriteLine(i.i);
    }
}

Is creating temporary objects like this frowned upon? Does the new object that is created get cleaned up properly.

like image 217
Firedragon Avatar asked Mar 08 '26 12:03

Firedragon


1 Answers

There is nothing wrong with that.

In release mode, creating a variable for the object should end up compiling to the same IL (disclaimer: I haven't checked).

like image 64
SLaks Avatar answered Mar 10 '26 01:03

SLaks



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!