Asad
Asad

Reputation: 21928

int? c#, used in ref, what exactly is it

might be a kiddy, biddy question but

I was trying to pass an "output" parameter to a Stored Procedure using C Sharp and was getting an error until I passed the "output" variable using following syntax:

int? ROWID = 0;
ADAPTER.INSERT(val1, val2, ref ROWID);

Though problem is solved, I just can't understand why, when I try to hold the value in a normal "int" returned by the stored proc it gives a conversion error

int result = ROWID; // not correct

So, what I have to do is:

int result = (int)ROWID; // correct

What exactly does "int?" mean?

Upvotes: 1

Views: 299

Answers (6)

Manish Basantani
Manish Basantani

Reputation: 17499

I would suggest this:

        int? ROWID = 0;
        ........
        int result = ROWID.HasValue ? ROWID.Value : 0;

Upvotes: 0

jball
jball

Reputation: 25014

int? is a nullable int. Read Using Nullable Types (C# Programming Guide).

By the way, if you don't read the whole guide, at least check out the HasValue and Value properties on your ROWID variable.

Upvotes: 9

Mark Byers
Mark Byers

Reputation: 838156

int? is the same as Nullable<int>, and means that the value can either be an integer, or the value null.

It's probably because your database column is set to NULL, instead of NOT NULL. If there can actually be null values in your database, your code will fail with an exception on the cast. If there can't be nulls in the database then you should change the schema definition for that column not NOT NULL so that it maps to int instead of int?.

Upvotes: 7

Mia Clarke
Mia Clarke

Reputation: 8204

It's a nullable type.

Read more about them here:

Nullable Types

Upvotes: 1

Paul Creasey
Paul Creasey

Reputation: 28824

int? is a nullable int (system.nullable), it can accept the value null.

Best way to convert is to null coallesce:

int result = rowid ?? 0;

Upvotes: 5

Phil Ross
Phil Ross

Reputation: 26100

int? is a nullable integer. See the MSDN page on Nullable Types for details.

Upvotes: 2

Related Questions