How to convert int? in int

I create a SPROC that saves the object and returns the identifier of the saved new object. Now I would like to return int not 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 the help

+7
c # linq-to-sql
source share
5 answers
 return id.Value; // If you are sure "id" will never be null 

or

 return id ?? 0; // Returns 0 if id is null 
+16
source share

You can use the GetValueOrDefault() function in Nullable.

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

Note that this is similar to Richard77's coalescing answer , but I would say a little more readable ...

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

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

You might want to check if id.HasValue is true and returns 0 or something if not.

+3
source share
 if (id.HasValue) return id.Value; else return 0; 
0
source share
 return id.HasValue ? id.Value : 0; 

this returns the id value if it is not equal to zero, and 0 otherwise.

0
source share

All Articles