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] });

1
  • 1
    can you also include what are your expected value? Commented Jun 19, 2019 at 7:59

3 Answers 3

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:

Sign up to request clarification or add additional context in comments.

3 Comments

I know, but i need to format this "s" string as in format. Something like this? I have to order it like in format string. var s = $"format";
Yeah so see the linked questions.
I fell so stupid right now. var format = "{var1},{var2}"; var finalString = $"{format}";
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 Comment

Thank you for answer, I cant give you upvote but it works quite good :)
-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]);

1 Comment

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 ideone.com/mmf3PQ.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.