C# null syntax

I remember being told that you can add some syntax to the end of a statement that will do something if the field is null. Pretty vague, but I cant seem to find anything about it via google.

I definitely isnt how to set a field to be nullable. I know that.

Here is an example of what I want.

int? field1 = 0;

field1 = int.parse(string2); (where string2 is a passed value, that could be null)

I thought there was something you could put at ?? that would help if it is a null, such as:

field1 = int.parse(string2) ??;

Or do I have to check every if every string2 is null before making that statement.

Well, I see there is a int.TryParse that I could use.

But I still am curious about the ?? above. Anybody know what I am thinking about?

Ahh, found it - the null coalescing operator.

And I would format the statement as:

field1 = int.parse(string2) ?? null;

I still cant figure this out, and am about to go crazy. Please help me.

c# code

private string userData;
private int intNull;
private int  intzero = 0;

intzero = int.Parse(userData) ?? intNull;

I get a compile time error:
Operator ?? cannot be applied to operands of ‘int’ and ‘int’

And google sees those ?? and doesnt search right.

I’m actually not familiar with ??. I will have to look it up. In the meantime, why not use the if then else shortcut?

var resultValue = condition ? trueValue : falseValue;

I’ll get back to you on the ?? thing…

private string userData;
private int intzero;

if (int.TryParse(userData,out intzero))
 //do something

If you don’t want to check for null, you can’t use int.Parse, because it will throw an exception.

At best you can use this, but the previous solution is much better

userData=userData??"0" ;// set a default string value
intzero=int.Parse(userData); // now, userData can't be null but it can be empty :D and you still have to catch an exception

[EDIT]: waves at Praetor lol…

Ok, back. Your syntax is correct:

value = condition ?? onNullValue;

But in your example you aren’t using nullable ints (Parse returns an int). An int can’t be null. The statement makes no sense.

Here’s your answer:

namespace SimpleTests
public class UnitTest1
public void simple_test()
string source = "123";
int? parsed = int.Parse(source);
int result = parsed ?? 0;
Assert.AreEqual(123, result);

Serena/Praetor - thanks for responding. (got some sleep and feel better).

So I got this to work (it compiles):

private string userData;
private int intzero;

int.TryParse(userData,out intzero);

But what I really want to do is this:

private string userData;

int.TryParse(userData,out CurrentUser.IntProperty)

where IntProperty is a integer property of the object CurrentUser.

But I get a compile error that says, “A property, indexer or dynamic member access may not be passed as an out or ref parameter”

Sorry if I am being a pain. I am just trying to get some clean code without having tons of IF statements.

Thanks for any help!

Found this from http://stackoverflow.com/questions/1370238/passing-a-property-as-an-out-parameter-in-c

You’d have to explicitly use a field and “normal” property instead of an auto-implemented property:

public class Bob 
     private int value;
     public int Value
       get { return value; }
       set { this.value = value; }

Then you can pass the field as an out parameter:

Int32.TryParse("123", out bob.value); 

But of course, that will only work within the same class, as the field is private (and should be!).

Properties just don’t let you do this. Even in VB where you can pass a property by reference or use it as an out parameter, there’s basically an extra temporary variable.

If you didn’t care about the return value of TryParse, you could always write your own helper method:

static int ParseOrDefault(string text)
     int tmp;
     int.TryParse(text, out tmp);
     return tmp; 
// Then use:

bob.Value = Int32Helper.ParseOrDefault("123"); 

That way you can use a single temporary variable even if you need to do this in multiple places.

I think I will setup the ParseofDefault method as described above

Just make that into an extension method and have it available on any int.

how do you do that?

Well…I’d make a string extension:

namespace MyProject.Extensions
    public static class StringExtensions
        public static int ParseOrDefault(this string sourceText, int defaultValue = 0)
                return int.Parse(sourceText);
                return defaultValue;

Now as long you have a using clause for the namespace, all strings have this new method.

string input = "234";
int result = input.ParseOrDefault(); // result = 234
string input = null;
int result = input.ParseOrDefault(); // result = 0
string input = "";
int result = input.ParseOrDefault(); // result = 0
// using a different default value
string input = "";
int result = input.ParseOrDefault(99); // result = 99 

It is better to use int.TryParse. Exceptions (when thrown) are horribly slow and may mess up your ability to debug. Only use exceptions for truly exceptional conditions.

Consider somthing like

int value;
if (!int.TryParse(somestring, out value)) value=0;

Doesn’t TryParse simply wrap parse in a try-catch internally, amounting to the same thing?

Yup, whatever.TryParse will not bubble exceptions – that is kind of the point of the method. Instead, it returns false if the value could not be parsed and does not change the value of the out parameter.

Believe it or not, in 1.0 days, how one should parse integers was a matter of huge debate. The old speed tests are still around somewhere.

No - TryParse does not throw exceptions. It is actually the other way around: Parse will call the same methods as TryParse internally but it will validate the results and throw exceptions explicitly.

Exceptions cause stack unwinding and has a considerable overhead when thrown. Installing an exception handler (try-catch block) is very effective as long as exceptions are not actually thrown. You could say that exceptions have been optimized for the the sunshine cases. Which makes sense: You want to make it easy and effective to code robust. After all, you should never expect exceptions - which is kind of implied by the name.

Hm. I learned something. TryParse does not wrap it’s code internally with a try-catch and silently consume it. Interesting…