Compiler error or code error?

2

I came across the following case and I do not know if it is a .Net error or error in my implementation, syntax itself (see image below).

condenacaoInsert.qtd_ano_pena=null;condenacaoInsert.qtd_ano_pena=(!string.IsNullOrEmpty(readerCondenacao["qtd_ano_pena"].ToString())) ? int.Parse(readerCondenacao["qtd_ano_pena"].ToString()) : null;
condenacaoInsert.qtd_mes_pena = (!string.IsNullOrEmpty(readerCondenacao["qtd_mes_pena"].ToString())) ? int.Parse(readerCondenacao["qtd_ano_pena"].ToString()) : null;
condenacaoInsert.qtd_dia_pena = (!string.IsNullOrEmpty(readerCondenacao["qtd_dia_pena"].ToString())) ? int.Parse(readerCondenacao["qtd_ano_pena"].ToString()) : null;

Error message:

  

Error 1 Type of conditional expression can not be determined because there is no implicit conversion between 'int' and '' (...)

    
asked by anonymous 19.03.2015 / 16:01

1 answer

4

It is extremely rare for you to find a compiler error. Never consider this until you have a very strong motive. How many times have you found a real compiler error? In dozens of languages I programmed in over 30 years, some with not very good compilers, I found little more than 2 or 3 compiler errors and nothing serious. And look what programming languages is the subject that I like most in computing. Of course I'm not counting on errors that I found in my compilers:)

In this case you are either returning an integer (first condition result) or a null. This is very explicit in the code.

A variable can not be integer or null. qtd_ano_pena must be of type int . The type int does not accept null values. Or you have to ensure that the result gives an integer, a zero, for example, if it is a suitable value, or you will have to change the type of this variable. You can switch to a int? that is an integer type that accepts nulls. his name is null and void. Of course it would be good to understand your entire operation because you may have other problems elsewhere if you use it.

After the comment below the author I realized that an explicit cast is missing in the first expression, since it results in integer and you want a nullable integer, so ants of the expression should put a (int?) . So I could do so much:

condenacaoInsert.qtd_ano_pena = 
     (!string.IsNullOrEmpty(readerCondenacao["qtd_ano_pena"].ToString())) ?
     (int?)int.Parse(readerCondenacao["qtd_ano_pena"].ToString()) : null;

how much

condenacaoInsert.qtd_ano_pena = 
     (!string.IsNullOrEmpty(readerCondenacao["qtd_ano_pena"].ToString())) ? 
     int.Parse(readerCondenacao["qtd_ano_pena"].ToString()) : (int?)null;
    
19.03.2015 / 16:09