0

I want to create a google translator link, that depends on my input. To make things clearer, here my "dynamic link":

private static string _GoogleLink = $"https://translate.google.com/?hl=de#{_SourceLanguage}/{_TargetLanguage}/{_SourceInput}"

I think it´s clear what i try to do, but the link doesn´t work this way, it just enters

https://translate.google.com/?hl=de#//

in my browser. I execute the link with this method:

public static void Translate(string input, string sourceLang, string targetLang)
{
    _SourceInput = input;
    _TargetLanguage = targetLang;
    _SourceLanguage = sourceLang;

    System.Diagnostics.Process.Start(_GoogleLink);
}
Rand Random
  • 7,300
  • 10
  • 40
  • 88
  • Have you debugged your code and checked whether the parameters contain the correct values? Also: From the code snippet you provided the use of a static field in the class seems not necessary. – Markus Safar Oct 30 '18 at 07:47
  • 1
    static variables are evaluated in the static constructor, `_GoogleLink` does not get evaluated again in the Translate method. – kennyzx Oct 30 '18 at 07:49
  • The $ is just a shortcut to string formatting. The formatting doesn't happen anytime you change the values of _SourceInput etc... but only when you define the string _GoogleLink_ and this being a static string is defined before your code reaches the Translate method. Just move the _GoogleLink_ as local variable inside the _Translate_ method – Steve Oct 30 '18 at 07:49
  • Duplicate of [this one](https://stackoverflow.com/a/26977877/107625). – Uwe Keim Oct 30 '18 at 07:51
  • If your question got answerd pls accept it - https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Rand Random Oct 30 '18 at 08:48

1 Answers1

1

Your static field gets evaluated upon the static creation, it never gets "updated" with the correct values - use a property instead of an field, which gets evaluated every time the getter is called.

private static string _GoogleLink => $"https://translate.google.com/?hl=de#{_SourceLanguage}/{_TargetLanguage}/{_SourceInput}";

Or old School Syntax

private static string _GoogleLink { get { return $"https://translate.google.com/?hl=de#{_SourceLanguage}/{_TargetLanguage}/{_SourceInput}"; } }

But you should consider re-designing your method to this:

//instead of void - use string as a return
public static string Translate(string input, string sourceLang, string targetLang)
{
    //instead of saving your passed values, into static fields - transform the string right here and now and return it
    return $"https://translate.google.com/?hl=de#{sourceLang}/{targetLang}/{input}";
}

I believe this syntax is more understandable.

Rand Random
  • 7,300
  • 10
  • 40
  • 88