This is a part of series on my quest to devour this book and share any interesting things that I didn’t know before:
This book is currently only available at Amazon. Singapore’s National Library only have its previous edition:
So C# 7.0 introduces new syntax sugar in if-else statement. Say we receive an object as a parameter for arithmetic operation. To prevent runtime error, we need to ensure that the parameter is an integer. The old way of doing this would be:
public static int someArithmeticOp(object o) {
    try {
        var i = (int) o;		
        // ..
        // .. do the arithmetic ops here 
        //..
    }
    catch (Exception ex) {
        throw;
    }		
}
With C# 7.0, we can do this:
public static int someArithmeticOp(object o) {    
    if (o is int i) {		
        // ..
        // .. do the arithmetic ops here 
        //..
    }
    else {
        // o is not integer, you can throw Exception, or doing other useful steps
        throw new Exception("Invalid parameter");
    }		
}
loading...
About Hardono
Incoming Search
.net, c#

 
