Navigate to Post

Tuesday, April 7, 2020

Learn C#~#4 Positional Pattern

Positional pattern match uses deconstruct feature. If an object provides a deconstruct method, we can use that object for a positional pattern match to match on the properties.

In the example, we will find the grade of a student based on his/her theory(80) and practical(20) marks.We will use a deconstruct to get tuple out of an object, and then pattern match on the object.


PROGRAM


using System;

namespace MyTestConsole
{
    class Program
    {
        static void Main()
        {
            ExamResult result = new ExamResult(70, 11);
            Console.WriteLine($"Grade of result with theory: {result.Theory} and Practical: {result.Practical} is: {CalculateGrade(result)}");

            Console.ReadKey();
        }

        private static Grade CalculateGrade(ExamResult result) => result switch
        {
            var (x, y) when (x + y) >= 81 => Grade.A,
            var (x, y) when (x + y) >= 61 && (x + y) < 81 => Grade.B,
            var (x, y) when (x + y) >= 41 && (x + y) < 61 => Grade.C,
            var (x, y) when (x + y) >= 33 && (x + y) < 41 => Grade.D,
            var (x, y) when (x + y) < 33=> Grade.E
        };
    }
    public class ExamResult
    {
        public double Theory { get; }
        public double Practical { get; }
        public ExamResult(double theory, double practical) => (Theory, Practical) = (theory, practical);
        public void Deconstruct(out double theory, out double practical)
        {
            (theory, practical) = (Theory, Practical);
        }
    }
    public enum Grade
    {
        A, B, C, D, E
    }
}

OUTPUT





All time trending post