What causes the 'System.NullReferenceException'?

4
Sometimes the execution of my systems is interrupted by this error, when it happens, a if(atributo != null) usually resolves, but this pollutes the code, "Ah, but this variable must have a value right?" the problem happens just when I assign a value while filling in the attributes of an object, this error appears.

  

"An exception of type 'System.NullReferenceException' occurred in ProjectName.dll but was not handled in user code" *

I have an associative class that saves Permissoes of a page and the user that has this permission, while I try to fill the associative ( FluxoUsuario ) it points the error:

Here is the excerpt from FluxosController.cs :

for (int i = 0; i < vwfluxo.Usuarios.Count(); i++)
                {
                    if (Request.Params["cb" + i] != null) 
                    {
                        FluxoUsuario fu = new FluxoUsuario();

                        var a = bool.Parse(Request.Form["cb" + i].Split(',')[0]);
                        var b = Request.Params["rb" + i]; //Pega valor do radioButton

                        if (a)//Verifica se a checkBox está marcada
                        {
                            if(db.FluxoUsuario.ToList().Where(x => x.Usuario.Equals(vwfluxo.Usuarios[i])).Count() > 0 == true)
                            {

                            }

                            fu.Fluxo.FluxoID = fluxo.FluxoID; //O Erro acontece nessa linha.
                     //fu.Fluxo é do tipo Fluxo, FluxoID é int. fu.Fluxo.FluxoID realmente precisa estar null quando acontece o erro, afinal, está sendo atribuido um valor para ele nesse momento.

                            fu.Usuario.IDUser = vwfluxo.Usuarios[i].IDUser;

                            fu.Fluxo = fluxo;
                            fu.Usuario = vwfluxo.Usuarios[i];

                            if (b == "ler")
                                fu.TipoPermissao = TipoPermissao.Ler;
                            else
                                fu.TipoPermissao = TipoPermissao.LerEscrever;

                            if (!fluxo.UsuariosPermitidos.Contains(fu))
                            {
                                fluxo.UsuariosPermitidos.Add(fu);
                            }
                        }


                    }
                }
    
asked by anonymous 30.12.2015 / 13:53

1 answer

7

Cause for trying to access a variable that should have a object by reference and has nothing, that is is null, that is, it was not initialized with a value. This never occurs on objects by value, unless you modify them to be nullable.

When the error occurs, there is a programming error. So the programmer should fix it and not try to do something miraculous in the code. It is very rare to want to handle an error of this type, at most it should logar and warn the user that there has been a programming error (I know the person will disguise it and say it is not programming error, nobody wants take the blame :)).

If the object should not be null, then have to figure out why it is and fix it. If it is null it is a possibility to be considered as normal, perhaps because it indicates some previous failure. In cases where it is expected to have a null object the most common solution really is to check if it is in this state and not let the access occur in any case.

In C # 6 you can use the null propagation operator that avoids access to the object when it is null. But it takes a bit of care, because this avoids error, but doing nothing can be a wrong action to take.

Objects by reference are usually initialized with the operator new ( string has a literal, some methods return a new object). This is initializing the object, trying to access its members to put data therein will produce an error because the object does not exist. It must first exist, then put values inside.

new will call a default builder or created by the programmer for that type.

Specific case

It would have to see how the object of type FluxoUsuario is being constructed. The fu variable is not null, it's easy to see. But the Fluxo member - which is a variable too - is part of it, was not initialized anywhere in the code presented. Has it been initialized by the FluxoUsuario constructor or by default in its declaration? I doubt, then either need to put this in type or else do this manually in this code. I prefer the first solution. Then% will no longer be null and this value will no longer run. Of course it can happen elsewhere. It has a face that will also occur in fu.Fluxo . I can not just say with the information presented.

    
30.12.2015 / 14:09