Sign in to follow this  
Kaze

[.net] easy way to avoid null strings?

Recommended Posts

//Is their a easy way to replace null strings with ""
//It would be nice if their was a less bulky way to turn

        public string ImageName { get; set; }

//into

        string imageName;
        public string ImageName {
            get { 
                if (imageName == null){
                    return "";
                }else{
                    return imageName;
                }
            }
            set { 
                imageName = value; 
            } 
        }

//the latter works except I have a fairly large number of property's I need to change

Share this post


Link to post
Share on other sites
Well, first off it'd probably be better (depending on your usage pattern) to replace the string in the setter so the conditional is checked less often.

Secondly, there's the null coalescing operator:


public string foo{
set{
internalFoo = value ?? ""; // assign value unless value is null, then ""
}
}




And I wouldn't be surprised if there was a publically available solution for something like this since it's common enough to have come up before.

Share this post


Link to post
Share on other sites
There's also string.IsNullOrEmpty() for testing strings. Also, prefer the usage of string.Empty over "", it's much more explicit and readable.

Share this post


Link to post
Share on other sites
I'm trying the null coalescing operator now to save a bit of code. The key issue here is that I thought string was a struct when I started so I'm a bit limited on what solutions I can use without having to rewrite half my project.
EDIT:
though to be fair its because all the other types that started with lower case were structs

Share this post


Link to post
Share on other sites
Quote:
Original post by Kaze
EDIT:
though to be fair its because all the other types that started with lower case were structs
Apart from object, of course. [wink]

Share this post


Link to post
Share on other sites
Or just be sure to always initialize strings.


class Test
{
string str;

public Test()
{
str = "";
Str2 = "";
}

public string Str
{
get { return str; }
}
public string Str2 { get; set; }
}

Share this post


Link to post
Share on other sites
Initializing to a default value isn't good enough for this since the classes I'm having the null string problem with are for serializing and deserializing game data and I want to keep the game engine from exploding even if the external data files are corrupted.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this