I'm joining a load of strings to make a superstring but i need to ignore a param if one is null. Currently i cannot think how to do this other than emcompassing all the params in seperate if statements. Help pls:
Here the code
public void LinkBuilder(string baselink, string sharedkey, string service, string period, string bulletintype,
string includeresults, string includemap, string username, string password)
{
sharedkey = "&" + sharedkey;
service = "&" + service;
period = "&" + period;
bulletintype = "&" + bulletintype;
includeresults = "&" + includeresults;
includemap = "&" + includemap;
username= "&" + username;
password = "&" + password;
string completeLink = sharedkey + service + period + bulletintype + includeresults + includemap + username +
password;
Not sure how to tackle this.
Any() internally attempts to access the underlying sequence ( IEnumerable ). Since the object can be null, there is no way to access the enumerable to validate it, hence a NullReferenceException is thrown to indicate this behavior.
In practice, NULL is a constant equivalent to 0 , or "\0" . This is why you can set a string to NULL using: char *a_string = '\0'; Download my free C Handbook!
NotNull: A nullable field, parameter, property, or return value will never be null. MaybeNullWhen: A non-nullable argument may be null when the method returns the specified bool value. NotNullWhen: A nullable argument won't be null when the method returns the specified bool value.
I would really refactor it this way:
public void LinkBuilder(params string[] links)
{
string completeLink = String.Join("&", links.Where(x=>!String.IsNullOrEmpty(x)));
}
If the objective is to avoid wrapping each parameter in an if statement, you could add them to a list, then use String.Join
, and Linq.Select
public void LinkBuilder(string baselink, string sharedkey, string service, string period, string bulletintype,
string includeresults, string includemap, string username, string password)
{
var allParams = new List<string>
{
baselink,
sharedkey,
service,
period,
bulletintype,
includeresults,
includemap,
username,
password
};
var completeLink = "?" + String.Join("&", allParams.Select(p => p != null));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With