tags:

views:

208

answers:

5

Hello,

I've create a SPROC that saves an object and returns the id of the new object saved. Now, I'd like to return an int not an int?

public int Save(Contact contact)
{
  int? id;
  context.Save_And_SendBackID(contact.FirstName, contact.LastName, ref id);
  //How do I return an int instead of an int?
}

Thanks for helping

+16  A: 
return id.Value; // If you are sure "id" will never be null

or

return id ?? 0; // Returns 0 if id is null
Philippe Leybaert
Note that `id.Value` will throw an exception when id is null. In some contexts, that will be appropriate, otherwise, use `??`.
Eric Mickelsen
Isn't this what I suggested?
Philippe Leybaert
Does `??` only work with Nullable<>, or also regular reference types?
Nelson
if works with all reference types. `x ?? y` is basically shorthand for `x!=null ? x : y`
SWeko
Great, thanks. I knew what it did, but just had that question pop in my mind.
Nelson
+3  A: 
return id.Value;

You might wanna check if id.HasValue is true, and return 0 or something if not.

PMN
+1  A: 
if (id.HasValue) return id.Value;
else return 0;
luvieere
or **return id??0**. Exactly the same :)
Philippe Leybaert
That's a rather long-winded way of saying "`id ?? 0`"
Blorgbeard
@Blogbeard: Technically, it would be `return id ?? 0;` :)
Nelson
@Philippe - actually, it isn't *quite* the same; the value as written checks *twice* whether a value is assigned. The `??` approach checks **once**. To check no times (and still behave 100% identically), you can use `return id.GetValueOrDefault()`.
Marc Gravell
@Marc: excellent remark. I didn't think about that one
Philippe Leybaert
+5  A: 

You could use the GetValueOrDefault() function on Nullable.

return id.GetValueOrDefault(0); // Or whatever default value is wise to use...

Note that this is similar to the coalescing answer by Richard77 but I would say slightly more readable...

However, deciding whether this is a good idea is up to you. Such that perhaps an exception is more appropriate?

if (! id.HasValue)
    throw new Exception("Value not found"); // TODO: Use better exception type!

return id.Value;
Reddog
+1 for suggesting that throwing an exception might be the appropriate thing to do. It seems to me that too many programmers are very quick to using a default value, without first making sure that null isn't really an error.
Phong
A: 
return id.HasValue ? id.Value : 0;

this returns the value of id in case it is not null and 0 in the other case.

obivandamme
What's wrong with `return id ?? 0;`, which does exactly the same thing and is more efficient?
Philippe Leybaert