browse by category or date

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");
    }		
}
GD Star Rating
loading...
C# 7.0 Pattern Matching In Conditional Logic, 3.0 out of 5 based on 1 rating

Possibly relevant:

About Hardono

Howdy! I'm Hardono. I am working as a Software Developer. I am working mostly in Windows, dealing with .NET, conversing in C#. But I know a bit of Linux, mainly because I need to keep this blog operational. I've been working in Logistics/Transport industry for more than 11 years.

Incoming Search

.net, c#

No Comment

Add Your Comment