0

I want to create string from variables based on format of another string. It passes only string names, not references. Ref is not working. What can i do?

var format = "city, post_code, street, building_number,name"
var city = model["City"];
var post_code = model["Post_Code"];
var street = model["Street"];
var building_number = model["Building_Number"];
var name = model["Name"];
var arguments = format.Split(",");
var s = String.Format("{0} {1} {2} {3} {4}", new object[] {  arguments[0],  arguments[1], arguments[2], arguments[3], arguments[4] });

Spiker
  • 31
  • 6

3 Answers3

3

You're trying to use strings as variable names. C# is not PHP.

What you actually want is string interpolation:

var s = $"{city}, {post_code}, {street}, {building_number}, {name}";

Now if you want this format string to be variable, see:

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

Not sure about the expected result/functionality here.

Is format a static Information or can it vary? I interpreted the question as the later is inteded. A (quite basic) solution could be:

    public void foo(DataRow model, String format = "city,post_code,street,building_number,name")
    {
        var arguments = format.Split(',');

        var val1 = model[arguments[0]];
        var val2 = model[arguments[1]];
        var val3 = model[arguments[2]];
        var val4 = model[arguments[3]];
        var val5 = model[arguments[4]];

        var s = $"{val1} {val2} {val3} {val4} {val5}";
    }
-1

You are not using the String.Format correctly. Modify your code like this

var s = String.Format("{0} {1} {2} {3} {4}", arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
Unknown
  • 58
  • 3
  • No. `arguments[0]` is "city", but the OP wants the _value of the variable named `city`_ to be printed there. Also, both you and the OP are using the `String.Format(string, params object[] args)` overload, both syntaxes call the same method. See also http://www.ideone.com/mmf3PQ. – CodeCaster Jun 19 '19 at 08:03