1

I'm trying to create an API call that will pass the parts of an address to an address verification service. The address must be passed as a single query parameter.

Using the following code

string input_address = HttpUtility.UrlEncode( string.Format( "{0} {1} {2} {3}",
            location.Street1, location.Street2, location.City, location.PostalCode ) );

The query succeeds if all parts of the address is present however if multiple parts are missing then + signs accumulate and you end up with a query like. /?api_key=####&query=++ID1+1QD&limit=1 which fails due to the extra '+' signs.

Is it possible to only pass values to a string if they are not null without using a set of if statements?

The full code is below:

string input_key = GetAttributeValue( "APIKey" );
string input_address = HttpUtility.UrlEncode( string.Format( "{0} {1} {2} {3}",
    location.Street1, location.Street2, location.City, location.PostalCode ) );

var client = new RestClient("https://api.ideal-postcodes.co.uk/");
var request = new RestRequest( Method.GET );
request.RequestFormat = DataFormat.Json;
request.Resource = "v1/addresses/";
request.AddParameter("api_key", input_key);
request.AddParameter("query", input_address);
request.AddParameter("limit", "1");
request.AddHeader("Accept", "application/json");
var response = client.Execute( request );
3
  • 1
    What's wrong with checking if a string is null or empty? Commented Feb 21, 2015 at 20:09
  • 1
    How does your validation service deal with missing parts? Commented Feb 21, 2015 at 20:11
  • String.IsNullOrEmpty? Commented Feb 21, 2015 at 20:16

1 Answer 1

5

To the core question, Is it possible to only pass values to a string if they are not null without using a set of if statements?

string[] addressParts = 
   { location.Street1, location.Street2, location.City, location.PostalCode};

string inputAddress = string.Join(" ", addressParts.Where(s=> !string.IsNullOrEmpty(s)));
inputAddress = HttpUtility.UrlEncode(inputAddress);
Sign up to request clarification or add additional context in comments.

Comments

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.