Cannot initialize a by-reference variable with a value C#

3k Views Asked by At

Having this error Cannot initialize a by-reference variable with a value I'm fairly new to C# just trying trying to fix up a abandoned open source project.

Here's the code:

private bool CertificateHandler(bool valueExist)
    {
      if (!CertMaker.rootCertExists() && !CertMaker.createRootCert() || (CertMaker.rootCertIsTrusted() ? 1 : (CertMaker.trustRootCert() ? 1 : 0)) == 0)
        return false;
      // ISSUE: explicit reference operation
      ref string local1 = @this.fiddlerCertInfos._fiddlerCert;
      if (local1 == null)
        local1 = FiddlerApplication.Prefs.GetStringPref("fiddler.certmaker.bc.cert", (string) null);
      // ISSUE: explicit reference operation
      ref string local2 = @this._fiddlerCertInfos._privateKey;
      if (local2 == null)
        local2 = FiddlerApplication.Prefs.GetStringPref("fiddler.certmaker.bc.key", (string) null);
      if (!valueExist)
        this.appRegistry.UpdateRegistry(new List<RegistryInfo>()
        {
          new RegistryInfo()
          {
            Name = "FiddlerCert",
            Value = (object) this._fiddlerCertInfos._fiddlerCert,
            RegistryValueKind = RegistryValueKind.String
          },
          new RegistryInfo()
          {
            Name = "PrivateKey",
            Value = (object) this._fiddlerCertInfos._privateKey,
            RegistryValueKind = RegistryValueKind.String
          }
        });
      return true;
    }

Error line:

ref string local1 = @this.fiddlerCertInfos._fiddlerCert;
ref string local2 = @this._fiddlerCertInfos._privateKey;
1

There are 1 best solutions below

2
olabacker On BEST ANSWER

Read this:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref#ref-locals

You can't assign a local reference variable with a non reference value. So either you need to remove the ref-keyword for the local variable or add 'ref' in front of the value which is assigned.