Sign in to follow this  

[.net] easy way to avoid null strings?

This topic is 3369 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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
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

This topic is 3369 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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