What causes the 'System.Nullreferenceexception'?

Asked

Viewed 6,047 times

5

Time or other the execution of my systems are interrupted by this error, when it happens, a if(atributo != null) It usually does, but it pollutes the code, "Oh, but this variable needs to have a value right?" the problem happens just when I will assign a value while filling the attributes of an object, this error appears.

"An Exception of type 'System.Nullreferenceexception' occurred in Nomedoprojeto.dll but was not handled in user code"*

I have an associative class that keeps Permissoes of a page and the user who has this permission, while trying to fill in the associative (FluxoUsuario) he points out the error:

Follows part of 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);
                            }
                        }


                    }
                }
  • If you are trying to define the value of an object property, for example Objeto.Nome, and the object is null this error occurs. If you post the exact snippet where the error occurs, I can help more.

1 answer

7


Because of trying to access a variable that should have one object by reference and has nothing there, that is, it is null, so it has not been initialized with a valid value. This never occurs in objects by value, unless you modify them to be voidable.

In C# 8 it is possible to connect a protection to never happen, as long as you program thinking about it always and have no legacies. Unfortunately people do not want to learn the novelties of language and are suffering with problems that should already be overcome.

When the error occurs it means there is a programming error. Then the programmer should fix it and not try to do something miraculous in the code. It is very rare to want to manipulate a mistake of this kind, at most it must log in and warn the user that there has been a programming error (I know the person will disguise and say that it is not programming error, no one wants to take the blame :) ).

If the object shouldn’t be null, then you have to find out why it’s null and void. If it is null is a possibility to be considered as normal, perhaps by indicating some previous failure then it must take certain precautions. 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 take place under any circumstances.

In C# 6 it is possible to use the operator of null Propagation which prevents access to the object when it is null. But a little caution is needed, 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 inside it will produce an error because the object does not exist. He must first exist, then put values inside.

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

Specific case

You’d have to see it as the object of the type FluxoUsuario is being built. The variable fu is not null, you can easily see. But the member Fluxo - which is a variable too - it’s part of it, it hasn’t been initialized anywhere in the displayed code. It was initialized by the constructor FluxoUsuario or by default in your statement? I doubt, so either you need to put this on the type or else do it manually in this code. I prefer the first solution. There fu.Fluxo will no longer be null and this error will no longer run. Of course it may occur in other places. There is a face that will also occur in fu.Usuario. I can’t say with just the information presented.

  • Thank you very much friend, total mistake of my own, when trying to fill only the fu ID. Flow, the rest of the attributes were null, removing the lines where it assigned the isolated ID and passing a complete object to it was possible to solve the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.