a simple question:
Is there a syntax for this kind of operation in C#:
- If condition, return the object itself : default value
Like in below example, but I don’t want to evaluate the myObject twice (which could be some much more complicated thing like database query):
int myVar = (myObject == DBNull.Value ? 0 : (int)myObject);
I know there is syntax for this when checking null (like in below example), but is there for checking any different value, like DBNull.Value in this case?
int myVar = Convert.ToInt32(myObject ?? 0);
No:
Is the best you can do. It doesn’t evalutate the object twice just because it is mentioned twice.
Or wrap it in a function of course:
Another option is using
Coalescein your SQL, so you don’t even get a DBNull in the first place.