What is the "default" returned by the Enumerable.SingleOrDefault method?

I wrote this piece of code to search for "Vendor" (Salesman), which satisfies the condition for the same "codigo" (id) entered by the TextBox user:

using (TccContext context = new TccContext()) { Vendedor[] query = (from vendedor in context.Vendedores where vendedor.codigo == Convert.ToInt64(this.textBoxProcurarCodFuncionario.Text) select vendedor).ToArray(); if (query.Length == 1) { textBoxCodigo.Text = query[0].codigo.ToString(); textBoxNome.Text = query[0].nome; textBoxTotalVendaMensal.Text = query[0].totalVendaMensal.ToString(); } else { MessageBox.Show("Código não encontrado,\n tente novamente...", "Atualizar Funcionário", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Limpar(); } } 

I would like to replace the ToArray method for SingleOrDefault, but I'm stuck in:

Returns a single element of a sequence or the default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

In this case, what will be the “default” as indicated in the documentation, I would like to be able to handle this “exception”, but I don’t know what it is?

Can someone explain to me what will be the "default"? I just started using Entity Framework, so not too much with me.

Thanks in advance.

+4
source share
4 answers

default(T) returned, which means null for reference types and a value of zero for value types.

default(T) will return null for reference types and zero for numeric value types. For structs, it returns each member of the structure, initialized to zero or null, depending on whether they are values ​​or reference types. For value types with a null-value, default returns a System.Nullable<T> , which is initialized like any structure.

+3
source

For types with a null value, the default value will be null.

For an integer its 0, and I think that all the other numbers too. I will see if I can find the documents ...

"The default value for reference and null types is null."

http://msdn.microsoft.com/en-us/library/bb342451.aspx

+1
source

The default value for types with null types and reference types (this will be your Vendor class) is null .

For default values ​​for other types, you can see this table of default values . It is usually 0, even for enums ; this can be problematic if you manually specified the values ​​in enum .

+1
source

For types with a null value, it is null, and for integers it is 0

From here : -

The default value for reference and null types is nullptr.

The SingleOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default (TSource), use DefaultIfEmpty (IEnumerable, TSource)

0
source

Source: https://habr.com/ru/post/1498863/


All Articles