How to do ToString for a possibly null object?

C# 6.0 Edit: With C# 6.0 we can now have a succinct, cast-free version of the orignal method: string s = myObj?.ToString() ?? “”; Or even using interpolation: string s = $”{myObj}”; Original Answer: string s = (myObj ?? String.Empty).ToString(); or string s = (myObjc ?? “”).ToString() to be even more concise. Unfortunately, as has … Read more

How to check a string against null in java?

string == null compares if the object is null. string.equals(“foo”) compares the value inside of that object. string == “foo” doesn’t always work, because you’re trying to see if the objects are the same, not the values they represent. Longer answer: If you try this, it won’t work, as you’ve found: String foo = null; … Read more

“Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions” error

I had the same problem with something like @foreach (var item in Model) { @Html.DisplayFor(m => !item.IsIdle, “BoolIcon”) } I solved this just by doing @foreach (var item in Model) { var active = !item.IsIdle; @Html.DisplayFor(m => active , “BoolIcon”) } When you know the trick, it’s simple. The difference is that, in the first … Read more

How do I find out if first character of a string is a number?

Character.isDigit(string.charAt(0)) Note that this will allow any Unicode digit, not just 0-9. You might prefer: char c = string.charAt(0); isDigit = (c >= ‘0’ && c <= ‘9’); Or the slower regex solutions: s.substring(0, 1).matches(“\\d”) // or the equivalent s.substring(0, 1).matches(“[0-9]”) However, with any of these methods, you must first be sure that the string … Read more