0

I have a problem with converting object to integer. I get NullReferenceException every time i run my code. Is there any way to omit it ? The problem is about "public static implicit operator int".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Item
    {
        int number;

        public Item(int number1)
        {
            number = number1;
        }

        public static implicit operator int (Item item)
        // convert item to int
        {

            return item.number;
        }
        public static implicit operator Item(int number)
        // convert int to item
        {
            return new Item(number);
        }
    }
}
Tamir Vered
  • 10,187
  • 5
  • 45
  • 57
davoid
  • 327
  • 2
  • 10

2 Answers2

2

We'd need to see the code where you're converting this object to an integer, but this sort of thing can happen if your calling code looks like this:

Item item = null;
int i = item;

The compiler will turn that into something roughly equivalent to this (provided this was syntactically valid):

Item item = null;
int i = Item.operator_int( item );

Since item is null, that's what gets passed into your operator and when you try to get the number field from item (which is null), it'll throw a NullReferenceException. You need to check if item is null in your operator.

Kyle
  • 6,500
  • 2
  • 31
  • 41
2

The Item where you implicitly cast to an int is null, for example:

Item item = null;
int a = item; //Will call the implicit operator with null
Console.WriteLine(a);

The middle line will call the implicit operator with null which will cause it to look for item.number where item is null and will throw a NullReferenceException as if you would write the following:

Item item = null;
int a = Item.operator_int(item);
Console.WriteLine(a);

You should change your operator to set a default value, for example:

public static implicit operator int (Item item)
{
    if (item == null)
    {
        return default(int); //0
    }
    return item.number;
}
Tamir Vered
  • 10,187
  • 5
  • 45
  • 57