//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
[.net] easy way to avoid null strings?
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:
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.
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.
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
EDIT:
though to be fair its because all the other types that started with lower case were structs
Quote:Original post by KazeApart from object, of course. [wink]
EDIT:
though to be fair its because all the other types that started with lower case were structs
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; }}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement