How to treat Nullreferenceexception with Lambda

Asked

Viewed 625 times

6

I have a class to search for DisplayName of my entities, where I pass the entity and class returns a list with the real values and name of each attribute of the entity.

My problem itself is when I do the search and some attribute in the entity does not have the annotation DisplayName. I get the error of 'System.NullReferenceException'.

I tried to put where for when you find some value null not list, but my mistake occurs when DisplayName:

.Where(p => p.GetCustomAttribute<DisplayNameAttribute>().DisplayName != null)

How can I solve this problem? because I will have entities with some attributes without displayname and I don’t want them to be selected.

Follows the codes:

Advanced research

public class PesquisaAvancada
{
    public String Valor { get; set; }
    public String Texto { get; set; }

    public static List<PesquisaAvancada> camposPesquisa<T>()
    {
        return typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
                       BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Where(p => p.GetCustomAttribute<DisplayNameAttribute>().DisplayName != null).
                                                                             Select(p => new PesquisaAvancada()
                                                                            {
                                                                                Valor = p.Name,
                                                                                Texto = p.GetCustomAttribute<DisplayNameAttribute>().DisplayName
                                                                            }).ToList();
    }
}

Entidade Cliente

public class Cliente
{
    [Key]
    [DisplayName("Identificador do Cliente")]
    public Guid ClienteId { get; set; }

    [Required]
    // aqui removi o display name e acusa o erro
    public String Nome { get; set; }
    [Required]
    [DisplayName("Nome Fantasia")]
    public String Fantasia { get; set; }
}

Error:

An unhandled Exception of type 'System.Nullreferenceexception' occurred in Model.dll

Image for a better understanding:

inserir a descrição da imagem aqui

3 answers

6

Just use the null-conditional operator of the C#.

If the return of p.GetCustomAttribute<DisplayNameAttribute>() for null no attempt will be made to access the property DisplayName and the result will be null.

.Where(p => p.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName != null)

Two questions it might be interesting to take a look:

  1. What is the operator "?."?

  2. What is the meaning of the operator "??"

See the example below working on . NET Fiddle.

using static System.Console;

public class Program
{
    public static void Main()
    {
        var customAttrName = GetCustomAttribute()?.DisplayName; 
        // Isto não estoura erro, ao invés disto, 'customAttrName' recebe null

        WriteLine(customAttrName ?? "Null"); //Null será a saída
    }

    public static CustomAttr GetCustomAttribute()
    {
        return null;
    }
}

public class CustomAttr
{
    public string Name;
    public string DisplayName;
}
  • The downvoter can you tell me what’s wrong with the answer so I can fix it?

  • Funny these downvoter without justification, could have a way to avoid this; Downvoter only be valid with a comment justifying and etc...

  • It is, but it’s complicated. This has already been quite discussed here on the site, but it really is a very delicate situation. Anyway, I wait feedback so I can fix the answer.

  • @jbueno understood its placement, when I put the operated ? I can’t find the available attribute anymore DisplayName using the Ctrl-Space command. .Where(p => p.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName != null) OBS: it wasn’t me who denied your answer. I appreciate the help

  • @Learner What language version are you using?

5


What is occurring is that you are trying to access a property of a null object

p.GetCustomAttribute<DisplayNameAttribute>().DisplayName != null

It is right to check whether the GetCustomAttribute returns a valid object, so its Where condition is:

.Where(p => p.GetCustomAttribute<DisplayNameAttribute>()!= null)

In the above code all properties that have the Displayname attribute are returned.

  • Right James understood, but at the time of Select I seek again the DisplayName and will occur NullReferenceException. How can I get the value in the text variable? of this location: Texto = p.GetCustomAttribute<DisplayNameAttribute>().DisplayName

  • 4

    After you have made this Where condition, you will have a collection of DisplayNameAttribute which are not null, so you can take the property DisplayName in the Select.

1

This Displayname returns a string or am I mistaken ?

Tries to replace:

p => p.GetCustomAttribute<DisplayNameAttribute>().DisplayName != null

for:

p => !string.IsNullOrEmpty( p.GetCustomAttribute<DisplayNameAttribute>().DisplayName));
  • 4

    Still an attempt will be made to access a member in the null return. What will pop an error.

Browser other questions tagged

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