Ryan Peschel
Ryan Peschel

Reputation: 11808

How to use object initializers with using statements?

Is there any way to refactor this code to not have to use a temporary variable and still use the syntactic sugar associated with object initializers?

FrmSomeForm someTempForm = new FrmSomeForm()
{
    SomePropA = "A",
    SomePropB = "B",
    SomePropC = "C"
};
using (FrmSomeForm someForm = someTempForm)
{
    someForm.ShowDialog();
}

Upvotes: 3

Views: 417

Answers (5)

Dmytro
Dmytro

Reputation: 17186

using (FrmSomeForm someForm = new FrmSomeForm(){
    SomePropA = "A",
    SomePropB = "B",
    SomePropC = "C"
})
{
    someForm.ShowDialog();
}

doesn't this work? oO

Upvotes: 4

Andrew
Andrew

Reputation: 835

You can do it like this

using 
(
    FrmSomeForm someForm = new FrmSomeForm()
    {
        SomePropA = "A",
        SomePropB = "B",
        SomePropC = "C"
    }
)
{
     someForm.ShowDialog();
}

Upvotes: 0

aleroot
aleroot

Reputation: 72636

using (FrmSomeForm someForm = new FrmSomeForm())
{
    someForm.SomePropA = "A";
    someForm.SomePropB = "B";
    someForm.SomePropC = "C";
    someForm.ShowDialog();
}

I think that is the simplest way and even the more readable in my opinion ...

Keep things simple :-)

Upvotes: 6

Mike Marynowski
Mike Marynowski

Reputation: 3439

using (FrmSomeForm someForm = new FrmSomeForm()
    {
        SomePropA = "A",
        SomePropB = "B",
        SomePropC = "C"
    })
{
    someForm.ShowDialog();
}

If you don't like the formatting, you can do something like this:

using (FrmSomeForm someForm = new FrmSomeForm() { SomePropA = "A", SomePropB = "B", SomePropC = "C" })
{
    someForm.ShowDialog();
}

Or:

private FrmSomeForm InitFrmSomeForm()  
{
    return new FrmSomeForm()
    {
        SomePropA = "A",
        SomePropB = "B",
        SomePropC = "C"
    };
}

using (FrmSomeForm someForm = InitFrmSomeForm())
{
    someForm.ShowDialog();
}

Upvotes: 0

AntLaC
AntLaC

Reputation: 1225

Try:

        using (FrmSomeForm someForm = new FrmSomeForm()
                        {
                            SomePropA = "A",
                            SomePropB = "B",
                            SomePropC = "C"
                        })
        {
            someForm.ShowDialog();
        }

Upvotes: 3

Related Questions