Reputation: 7025
I wrote this piece of code to look for one 'Vendedor' (Salesman) that satisfies the condition of having the same 'codigo' (id) entered in a TextBox by a 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'd like to replace the ToArray method for SingleOrDefault, but I got stuck with:
Returns the only element of a sequence, or a 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 would be a "default value" as said in the documentation, I'd like to be able to treat this "exception", but I don't know what it is?
Can someone explain me what would be this "default value"? I just started using Entity Framework so don't take too hard with me.
Thanks in advance.
Upvotes: 4
Views: 1098
Reputation: 9201
The default value for nullable types and reference types (This would be your Vendor
class) is null
.
For default values of the other types, you can look at this default value table. It is usually 0, even for enums
; this can be problematic if you manually specified the values in your enum
.
Upvotes: 1
Reputation: 46008
What is returned is default(T)
, which means null
for reference types and 'zero' value for value types.
default(T)
will return null
for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default
returns a System.Nullable<T>
, which is initialized like any struct.
Upvotes: 3
Reputation: 172568
For nullable types it is null and for integers it is 0
From here:-
The default value for reference and nullable 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 the DefaultIfEmpty(IEnumerable, TSource)
Upvotes: 0
Reputation: 4328
For nullable types default will be null.
For integer its 0, and I think all other numbers are as well. I'll see if I can find the docs...
"The default value for reference and nullable types is null."
http://msdn.microsoft.com/en-us/library/bb342451.aspx
Upvotes: 1