C# Error: Sequence contains no element

C# Error: Sequence contains no element

This error happen when I was trying to call Single() command like this:
Held holdData = new HeldBusinessLogic().Get(id: cId).Single();

Since there was no record in the Held table, the Single() command results in error: “Sequence contains no elements”

To fix the issue I had to change the code to:
Held holdData = new HeldBusinessLogic().Get(id: cId).FirstOrDefault();

The FirstOrDefault() returns null when there is no record whereas Single() tries to retrieve an element from the sequence

This error can also result when you attempt to execute any aggregate method on an empty result set.

Example
int maxData = context.Surface.Max(s => s.Surface.GetValueOrDefault());

To fix this:
int maxData = context.Surface==null?0: context.Surface.Max(s => s.Surface.GetValueOrDefault());

Another Filter example

Error
claim.Held.First(c => c.ClaimId == claimId);
Solution
claim.Held.FirstOrDefault(c => c.ClaimId == claimId);

However this can happen with the following commands also:
First() – use first when you know the sequence will have at least one element
FirstAsync() – Asynchronously returns the first element of a sequence.
SingleAsync() – Asynchronously returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
Last() – Returns the last element of a sequence.
LastOrDefault() – Returns the last element of a sequence, or a default value if the sequence contains no elements.
LastAsync()

C# Version History

C# Version History

Version Features Visual Studio Framework
C# 7.2 Reference semantics with value types
Non-trailing named arguments
Leading underscores in numeric literals
private protected access modifier
Visual Studio 2017 version 15.5 .NET Core/ .NET Framework 4.7.1
C# 7.1 async Main method
default literal expressions
Inferred tuple element names
Visual Studio 2017 version 15.3 .NET Framework 4.7
C# 7.0 out variables
Tuples
Discards
Pattern Matching
ref locals and returns
Local Functions
More expression-bodied members
throw Expressions
Generalized async return types
Numeric literal syntax improvements
Visual Studio 2017 .NET Framework 4.7
C# 6.0 Read-only Auto-properties
Auto-Property Initializers
Expression-bodied function members
using static
Null – conditional operators
String Interpolation
Exception filters
nameof Expressions
await in catch and finally blocks
index initializers
Extension methods for collection initializers
Improved overload resolution
Visual Studio 2015 .NET Framework 4.6
C# 5.0 Async / await, and caller information attributes. Visual Studio 2012 .NET Framework 4.5
C# 4.0 Dynamic binding
Optional parameters and named arguments
Type variance with generic interfaces and delegates
Generic co- and contravariance
Embedded interop types
Visual Studio 2010 .NET Framework 4.0
C# 3.0 LINQ
Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expressions
Expression trees
Partial Methods
Visual Studio 2008 .NET Framework 3.0\3.5
C# 2.0 Generics
Partial types
Anonymous methods
Iterators
Nullable types
Private setters (properties)
Method group conversions (delegates)
Covariance and Contra-variance
Static classes
Visual Studio 2005 .NET Framework 2.0
C# 1.1 #line pragma and xml doc comments. Visual Studio 2003 .NET Framework 1.0/1.1
C# 1.0 First initial release Visual Studio 2002 .NET Framework 1.0/1.1

C# Difference between ref and out parameters

In C# by default the parameters are always passed by value but you can also use out and ref keywords for passing parameters by reference.
Both keywords are identical with the only difference of initializing the value of the variable. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn’t differentiates between the two while it created IL for ref and out).

Sample Code

using System;
namespace HelloWorld
{
 class Hello 
 {
 static void Main() 
 {
     Console.WriteLine("**********Using Ref Method**********");     
     int num = 10;
     MyMethodRef(ref num);
     Console.WriteLine("Value Outer Method : {0}", num);
     
     Console.WriteLine("**********Using Out Method**********");
     int numout = 10;
     MyMethodOut(out num);
     Console.WriteLine("Value Outer Method : {0}", numout);
 }

 private static void MyMethodRef(ref int number){
    number += 20;
    Console.WriteLine("Value Inner Method : {0}", number);
 }
 
 private static void MyMethodOut(out int number)
 {
    number = 20;
    Console.WriteLine("Value Inner Method : {0}", number);
 }
 }
}

Output
**********Using Ref Method**********
Value Inner Method : 30
Value Outer Method : 30
**********Using Out Method**********
Value Inner Method : 20
Value Outer Method : 10

Using Ref
With Ref keyword, the objects is initialized first before used in the function, you need to set the value first then call in the method to read and modify. If you tried to pass num variable without initializing to the MyMethodRef() method, you’d end up with a compilation error: Use of unassigned variable ‘num‘.

Using Out
With Out keyword, the variable have to be assigned inside the function. A variable passed in using out cannot be read from before its assigned to.
The method must be set it before returning.

You can use out and ref parameters for overloading methods.
static void Method(String name){}
static void Method(ref String name){} //ok
static void Method(out String name){} //error

You can overload the standard method by using the ref or out keywords but cannot overload that differs only by out and ref simultaneously. The parameter’s type must match the type of the value that is passed.

C# List of String Functions

String Functions

string.IsNullOrEmpty()read more here

Code Sample:

string output = string.IsNullOrEmpty(someString) ? "0" : someString; 
 You can also use the null coalescing operator (??), but it would not handle empty strings. 
 string output = somePossiblyNullString ?? "0";

string.sNullOrWhiteSpace() – Indicates whether a specified string is null, empty, or consists only of white-space characters.

string.Empty – declare a empty string

string.ToUpper() – covert the string to uppercase

string.Split() – extracts sub-string in string

C# virtual vs override

Virtual vs Override

Virtual means making another version of same method in a child class, simply check for newer implementations before calling but abstract method is guaranteed to be overridden in all derived classes. In programming terminology it means that it can modify a method, property, indexer or event declaration and allow it to be overridden. A method cannot be overridden in a derived class unless it is declared as virtual or abstract. For abstract class no implementation is required in the base class because it will be redefined in the derived class.

When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used.

Example: Using override

using System;
namespace HelloWorld
{
 class Hello 
 {
    static void Main() 
    {
       Base b = new Derived();
       b.SomeMethod();

       Derived d = new Derived();
       d.SomeMethod();
    }
 }

public class Base {
     public virtual void SomeMethod()
     {
        Console.WriteLine("From base class"); 
     }
 }

public class Derived: Base {
     public override void SomeMethod()
     {
        Console.WriteLine("From derived class"); 
     }
 }
}

Output:
From derived class
From derived class

Example: Using New

using System;
namespace HelloWorld
{
 class Hello 
 {
    static void Main() 
    {
       Base b = new Derived();
       b.SomeMethod();

       Derived d = new Derived();
       d.SomeMethod();
    }
 }

public class Base {
     public virtual void SomeMethod()
     {
        Console.WriteLine("From base class"); 
     }
 }

public class Derived: Base {
     public new void SomeMethod()
     {
        Console.WriteLine("From derived class"); 
     }
 }
}

Output:
From base class
From derived class

Using the new keyword instead of override, the method in the derived class doesn’t override the method in the base class.
If you don’t specify new or override, the compiler will give a warning but the result output will be same as new.

Base b = new Derived();
Here I am creating the instance of Derived class but stored the reference in base. This is valid because Derived class is inherited from base. Derived class can perform all the operations that a base class can do but Base class will not be able to perform the operations of Derived class. Therefore you cannot reverse the declaration like Derived d = new Base().

When non-virtual method is called, the compiler already knows the actual method but for virtual methods the compiler has to lookup from down to up the hierarchy.

An overriding property declaration may include the sealed modifier. The use of this modifier prevents a derived class from further overriding the property. The accessors of a sealed property are also sealed.

C# Collection of reserved keywords

Keywords

A
abstract as
B

base
bool
break
byte

C

case
catch
char
checked
class
const
continue

D

decimal
default
delegate
do
double

E

else
enum
event
explicit
extern

F

false
finally
fixed
float
for
foreach

G

goto

I

if
implicit
in
int
interface
internal
is
lock
longnamespace
Main() – this is the method where your program starts running. When the program is first loaded it will look for the Main method.

N

new
null

O

object
operator
out
override

P

params
private
protected
—–
public
The public keyword exposes members to other classes.

using System;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Panda p1 = new Panda ("Pan Dee");
            Panda p2 = new Panda ("Pan Dah");
            
            Console.WriteLine(p1.Name);
            Console.WriteLine(p2.Name);

        }
    }
    
    public class Panda
    {
        //instance field
        public string Name;
        
        
        //Constructor
        public Panda (string n)
        {
            //Assign the instance field
            Name = n;
            
        }
    }
}

If instance field was declared private the program class will not be able to access it.

R

readonly
ref
return

S

sbyte
sealed
short
sizeof
stackalloc
Sealed
– Class cannot be inherited anymore
Static
– Static class cannot be instantiated, cannot use the new keyword, there is no instance variable. Contains only static members and is sealed.

static member – is callable when no instance of the class is created, not associated with an instance of the class

class SomeClass {
    public int InstanceMethod() { return 1; }
    public static int StaticMethod() { return 42; }
}


SomeClass instance = new SomeClass();
instance.InstanceMethod();   //Fine
instance.StaticMethod();     //Won't compile

SomeClass.InstanceMethod();  //Won't compile
SomeClass.StaticMethod();    //Fine

– You need to initiate your class to call InstanceMethod
– You cannot invoke non static method from static method
string
struct
switch

T

this
throw
true
try
typeof

U

uint
ulong
unchecked
unsafe
ushort
using – reserved word to instruct the compiler to include a namespace. eg using System; Using statement ensures that an object is disposed of when it goes out of scope.

V

virtual
void – keyword means that the method we are about to describe does not return anything, the method will not return anything.
volatile

W

while

Contextual keywords

A

add
ascending
async
await

B

by
descending
dynamic

E

equals

F

from

G

get
global
group

I

in
into

J

join

L

let

N

nameof operator
The nameof operator returns the name of any symbol (type, member, variable, and
so on) as a string:

int count = 123;
string name = nameof (count); // name is "count"
O

on
orderby

P

partial

R

remove

S

select
set

V

value
var

W

when
where

Y

yield