testing if int property has been initialised.

D

damiensawyer

Hi,

I've recently moved to c# framework 2 and have just discovered the
comiler warning "The result of the expression is always 'false' since
a value of type 'int' is never equal to 'null' of type 'int?'"

Can someone please tell me best practise for determining in properties
if an int has been initialised?

Thanks very much in advance,


Damien


private _remedyFieldCount
public int RemedyFieldCount
{
get
{
if (_remedyFieldCount == null) // The result of the
expression is always 'false' since a value of type 'int' is never
equal to 'null' of type 'int?'
{
_remedyFieldCount = ... do
initialisation }
}
return _remedyFieldCount;
}
 
P

parez

Hi,

I've recently moved to c# framework 2 and have just discovered the
comiler warning "The result of the expression is always 'false' since
a value of type 'int' is never equal to 'null' of type 'int?'"

Can someone please tell me best practise for determining in properties
if an int has been initialised?

Thanks very much in advance,

Damien

private _remedyFieldCount
public int RemedyFieldCount
{
get
{
if (_remedyFieldCount == null) // The result of the
expression is always 'false' since a value of type 'int' is never
equal to 'null' of type 'int?'
{
_remedyFieldCount = ... do
initialisation }
}
return _remedyFieldCount;
}


public int? Test
{ get; set; }

if (Test.HasValue)
{
}

this could work...
 
P

parez

public int? Test
{ get; set; }

if (Test.HasValue)
{
}

this could work...

this mite be better

private static int? _test;
public static int Test
{
get
{
if (_test.HasValue)
{

}
}
set
{
}
}
 
P

parez

public int? Test
{ get; set; }

if (Test.HasValue)
{
}

this could work...

I think the abouve does not compile.

private static int? _test;
public static int Test
{
get
{
if (!_test.HasValue)
{

}
return (int)_test;
}
set
{
_test = value;
}
}
 
A

Arne Vajhøj

I've recently moved to c# framework 2 and have just discovered the
comiler warning "The result of the expression is always 'false' since
a value of type 'int' is never equal to 'null' of type 'int?'"

Can someone please tell me best practise for determining in properties
if an int has been initialised?

You have a few options:

1) initialize it to a magic value like -1 and consider that value
uninitialized
2) add a bool field that indicates whether the int field is initialized
3) change the type from int to int? - then you can test for null
4) restructure the logic so that you will not need to test

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top