Home > Software engineering >  string with quotes in C#
string with quotes in C#

Time:09-29

How I can have a string value like "PropertyBag["ABCD"]" ? I want it to assign to a value of a chart in my WPF App. I am using it like as shown below :

   private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        ViewModel vm = new ViewModel();
        foreach (var str in vm.Data)
        {
            string name = "ABCD";
            LineSeries lineSeries = new LineSeries();
            lineSeries.ItemsSource = new ViewModel().Data;
            lineSeries.XBindingPath = "Date";
            lineSeries.YBindingPath = "PropertyBag[\"   name   \"]"; // here i am getting error saying - Input string was not in a correct format 
            lineSeries.IsSeriesVisible = true;
            lineSeries.ShowTooltip = true;
            chart.Series.Add(lineSeries);
        }
        this.DataContext = vm;
    }

I want it like lineSeries.YBindingPath = "PropertyBag["ABCD"]" // (should include all 4 double quotes). How it is possible ??

I tried this also, but still same error :

  lineSeries.YBindingPath = String.Format(@"PropertBag[""{0}""]", name);

CodePudding user response:

This must work and it is a more elegant solution:

string name = "ABC";
lineSeries.YBindingPath = string.Format("\"PropertyBag[\"{0}\"]\"", name);

You escaped the quote before and after name, in doing that you didn't specify where the first part of the string ends and where the second one starts. To avoid errors like that it is better to use the Format method. It makes code easier to read and maintain.

The following solution:

string.Format(@"""PropertyBag[""{0}""]""", name)

is good too, but I think the first one is more readable. I personally like more the first one. But it is up to you, just avoid concatenation; in modern programming it is deprecated especially when the language has more efficient and powerful tools to do the job.

CodePudding user response:

You're escaping the quotes before the pluses, meaning they get interpreted as characters, not as addition operators. You need to add additional quotation marks, like so:

lineSeries.YBindingPath = "PropertyBag[\""   name   "\"]";

This way, you define two new strings; a prefix and a suffix to the name variable.

CodePudding user response:

Quoted string literals

("PropertyBag[\""   name   "\"]");

Verbatim string literals

(@"PropertyBag[""{0}""]", name);

Try Raw string literals if you're on C# 11

  •  Tags:  
  • c#
  • Related