[.net] easy way to avoid null strings?

Started by
6 comments, last by Kaze 15 years, 7 months ago

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

Advertisement
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.
There's also string.IsNullOrEmpty() for testing strings. Also, prefer the usage of string.Empty over "", it's much more explicit and readable.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

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

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

And 'int' is really an alias for System.Int32. :)
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; }}
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.

This topic is closed to new replies.

Advertisement