Home > database >  How to reduce the code to one line or output it to a function?
How to reduce the code to one line or output it to a function?

Time:06-08

Good afternoon! I have a code that checks the value of three constants

var postgres =
    Registry.LocalMachine.OpenSubKey(Constants.PostgSQLRegKey   Constants.BID, true) ??
    Registry.LocalMachine.OpenSubKey(Constants.PostgSQLRegKey   Constants.CID, true) ??
    Registry.LocalMachine.OpenSubKey(Constants.PostgSQLRegKey   Constants.FID, true);

Is it possible to write it in one line or a separate function?

To avoid writing three times

Registry.LocalMachine.OpenSubKey(Constants.PostgreSQLRegKey)

CodePudding user response:

How about this

Func<string, RegistryKey?> openSubKey = (c) => 
    Registry.LocalMachine.OpenSubKey(Constants.PostgreSQLRegKey   c, true);

var postgresServicesKeyNew =
    openSubKey(Constants.BID) ??
    openSubKey(Constants.CID) ??
    openSubKey(Constants.FID);

This is generally how you could refactor this to reduce the duplication.

CodePudding user response:

Chipping in my own take:

using System;

namespace MyProject
{
    using static Constants; // <-- This brings `PostgreSQLRegKey`, `CID`, `BID`, and `FID` into scope without further qualification.

    public class MyClass
    {
        void Foobar()
        {
            // This is a static-local function, see here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/static-local-functions
            // Named "ow" for "open-writable" - or "ow!" because you're messing around in the Registry which you probably shouldn't be            
  •  Tags:  
  • c#
  • Related