Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore if var is null c#

Tags:

c#

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.

like image 768
marwaha.ks Avatar asked Sep 17 '15 13:09

marwaha.ks


People also ask

Does .ANY check for NULL?

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.

How do you say null in C?

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!

IS NOT NULL in C#?

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.


2 Answers

I would really refactor it this way:

public void LinkBuilder(params string[] links)
{
    string completeLink = String.Join("&", links.Where(x=>!String.IsNullOrEmpty(x)));
}
like image 80
Maksim Simkin Avatar answered Oct 06 '22 22:10

Maksim Simkin


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));
    }
like image 38
Stumblor Avatar answered Oct 06 '22 22:10

Stumblor