throw expressions C# with Example



throw expressions C# with Example

C# 7.0 allows throwing as an expression in certain places: 
class Person 
{ 
 

public string Name { get; } 
public Person(string name) => Name = name ?? throw new ArgumentNullException(nameof(name)); 
public string GetFirstName() 
{ 
var parts = Name.Split(' '); 
return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!"); 
} 
public string GetLastName() => throw new NotImplementedException(); 
} 
Prior to C# 7.0, if you wanted to throw an exception from an expression body you would have to: 
var spoons = "dinner,desert,soup".Split(','); 
var spoonsArray = spoons.Length > 0 ? spoons : null; 
if (spoonsArray == null) 
{ 
throw new Exception("There are no spoons"); 
} 
Or 
var spoonsArray = spoons.Length > 0 
? spoons 
: new Func(() => 
{ 
throw new Exception("There are no spoons"); 
})(); 
In C# 7.0 the above is now simplified to: 
var spoonsArray = spoons.Length > 0 ? spoons : throw new Exception("There are no spoons"); 

0 Comment's

Comment Form

Submit Comment