Tom
Tom

Reputation: 6707

typecast problem with List class

What is the bug here?

private void LoadUsers(List<long> uids, EventUser.EventUserStatus eventUserStatus, IList<user> chkfriends)
{
    foreach (var f in chkfriends) 
    {
      long l = f.uid; <-- fails
       if (uids.Contains(l)) do it!
    }

Error 1 Cannot implicitly convert type 'long?' to 'long'. An explicit conversion exists (are you missing a cast?)

Upvotes: 1

Views: 492

Answers (6)

Manish Basantani
Manish Basantani

Reputation: 17499

one more choice.

if (!f.uid.HasValue)   
    throw new NullReferenceException("Uid cannot be null");  
long l = f.uid.Value;  

Upvotes: 0

this. __curious_geek
this. __curious_geek

Reputation: 43207

uid is nullable so change your statement to this one and it should work.

long l = f.uid ?? 0;

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062865

f.uid is presumably long? - in which case just:

long l = f.uid.Value;

This assumes that the value of uid isn't empty. If there might be null ids in the set, then perhaps:

if(f.uid != null && uids.Contains(f.uid.Value)) {
    // do it!
}

Upvotes: 2

Daniel Br&#252;ckner
Daniel Br&#252;ckner

Reputation: 59655

Your local variable l is of type long while the field or property user.uid seems to be of type Nullable<long> (a.k.a. long?) - therefore the assignment is not allowed.

Upvotes: 0

driis
driis

Reputation: 164291

f.uid is nullable long (System.Nullable<long>), so you cannot assign it to a long.

Try:

long? l = f.uid;

Or perhaps:

if ( f.uid == null ) 
    throw new NullReferenceException("Uid cannot be null");
long l = f.uid.Value;

It might be an error situation if the uid is null, in that case it would be appropiate to throw an exception. You can read more about nullable types here.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

long l = f.uid.Value;

The bug is that f.uid is Nullable<long> and you are trying to assign it to long.

Upvotes: 0

Related Questions