Cannot implicitly convert type `long?' to `int'.

Hi there,

I’ve come across an error which says: Cannot implicitly convert type long?' to int’.

I’ve had a look online and lots of places are saying use Convert.ToInt32(). but that doesn’t to seem to work with unity.

I guess its a long because that is what the server used to store scores is setup to use. However I would like to just use an int.

Any ideas?

I can come up with many ways to make that error appear. As I’m not a magician, I can’t read your code over the internet. So unless you post whatever’s causing the issue, no ideas.

One note, though; the type long? means that the value is “a long or null”. If you have a struct Foo, the type Foo? is either Foo, or null. So if you’re getting a long?, and want to convert it to an int, you could do something like:

private int ToInt(long? value) {
    if (value.HasValue)
        return Convert.ToInt32(value);

    return 0; //the input value was null
}

Or just

(int)myLong
1 Like

If an external library is using long? instead of long, assume that they’re doing it for a reason, and do the HasValue check, or you’ll end up shiping a build that crashes due to InvalidOperationExceptions.

Since long? is a reference type, it’s default value is null, so the probability of a long? being null is really high - it just needs to not have been done anything with.

3 Likes

LONG TO INT: (8L is the long value)
int y = (int)8L;

INT TO LONG: (3 is the int value)
long y = (long)3;

You can check on the Documentation for C#:

You’ve resurrected a 3 year old thread to give the same answer that completely disregards the nullable part that Baste mentioned twice.

As long as we’re in a 3 year old thread anyway …

Nullable types are not reference types. long? is a value type.
Nullable types are just a struct containing a value of the generic type (which must be a value type) and a bool to indicate whether it has been assigned (or is “null”). Its default value is “null” because the default value of bool is false.

public struct Nullable<T> where T : struct
    {
        public Nullable(T value);

        public bool HasValue { get; }
        public T Value { get; }

        public override bool Equals(object other);
        public override int GetHashCode();
        public T GetValueOrDefault();
        public T GetValueOrDefault(T defaultValue);
        public override string ToString();

        public static implicit operator T? (T value);
        public static explicit operator T(T? value);
    }
2 Likes