Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any syntax to shorten setting variables on object in new C#

Im curious if there is any way to shorten this code, or make it in one line / statement,

        var terraformProcess = new Process();
        terraformProcess.StartInfo.FileName = "terraform";
        terraformProcess.StartInfo.UseShellExecute = false;
        terraformProcess.StartInfo.WorkingDirectory = Path.Combine(repoPath,"terraform");
        Console.WriteLine(terraformProcess.StartInfo.WorkingDirectory);
        terraformProcess.StartInfo.RedirectStandardOutput = true;
        terraformProcess.StartInfo.Arguments = "init";
        terraformProcess.Start();
        terraformProcess.WaitForExit();

        terraformProcess.StartInfo.Arguments =
            $"destroy --var-file=current.tfvars -auto-approve -var vcd_user={_terraformConf.vdcUsername} -var vcd_pass={CryptoServices.Decode(_terraformConf.encryptedVdcPass)} -no-color";
        terraformProcess.Start();
        var output = terraformProcess.StandardOutput.ReadToEnd();
        terraformProcess.WaitForExit();

Ive tried:

var startInfo = new StartInfo {
FileName = "terraform",
WorkingDirectory = Path.Combine(repoPath,"terraform");
RedirectStandardOutput = true;
Arguments = "init";
};

then assigning it to Process.StartInfo, but it looks like there is only getter on Process.StartInfo.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Im just curious if there is a shorter way of doing that, without repeating so many lines.

>Solution :

You can use object initializer syntax on multiple levels, i.e

var terraformProcess = new Process
{
    StartInfo =
    {
        FileName = "terraform",
        UseShellExecute = true,
        // etc ...
    }
};

You can read up more on object and collection initializers here, it’s an incredibly handy piece syntactic sugar

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading