C# swap variables from a configuration string

Markus Freitag 3,786 Reputation points
2021-03-03T13:59:17.867+00:00

Hello,

urlGetOrderPath ="api/getOrderData?orderId={orderId}"
urlGetOrderPathSize ="api/getOrderDataSize?orderId={orderId}xPos={xPos}"

 string urlParameters = Cfg.UrlGetOrderData.Replace("{orderId}", orderId);

I read in the strings via a file. Afterwards I exchange the variables. Is there a way to treat it as if it were a string?
Like this

    Log.Error($"[CUST][RequestNewOrder], ConnectFailure {ex.Status}");

That would spare the Replace.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,288 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.5K Reputation points
    2021-03-03T16:36:33.887+00:00

    Try using numbered (instead of named) parameters:

    string urlGetOrderPathSize = "api/getOrderDataSize?orderId={0}&Pos={1}";
    string result = string.Format( urlGetOrderPathSize, orderId, orderPos );
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Michael Taylor 48,581 Reputation points
    2021-03-03T14:55:45.607+00:00

    String interpolation, unfortunately, only works with compile time string literals. Therefore you cannot do string interpolation. This is mostly a compile time feature of the compiler. The compiler takes the interpolated string literal and rewrites it to the equivalent String.Format call. Hence at runtime there is no concept of string interpolation. However there is the special type FormattableString that it recognizes but that uses the same syntax as format strings so it doesn't help here. I don't know a way around this other than Replace. There are string template libraries you can definitely bring in to use but under the hood they are going to do the same thing as Replace.

    Personally I would question why the relative URLs would need to be in a configuration file to begin with. This just seems like over architecture to me. Yes URLs may change over time but this would break lots of code in most cases. Furthermore every use of the URL would take the hit of having to do a replacement. I would definitely make the root configurable but everything after that should be relative and consistent. If you go this route then you can define your URLs as const strings in code and accomplish basically the same thing. Of course string interpolation wouldn't work there as well but you could provide "generator" methods that could use string interpolation if desired. You could even go so far as to create a source generator that auto-generates the URLs (using string interpolation) at compilation time if you wanted.

    1 person found this answer helpful.
    0 comments No comments