What's new

C# C# switch case

PHC-Ime

Forum Veteran
Elite
Joined
Jan 7, 2015
Posts
1,049
Reaction
673
Points
521
Baka po may makatulong sa activity ko
“SWITCH-CASE Statement' in class”
C# po gamit namin
 
Sure, I'd be happy to help you with your activity on switch-case statement in C#.

The switch-case statement is used to evaluate an expression and execute a block of code based on the result of the evaluation. The basic syntax of the switch-case statement is as follows:

C#:
switch (expression)
{
    case value1:
        // code to execute when expression is equal to value1
        break;
    case value2:
        // code to execute when expression is equal to value2
        break;
    // more cases can be added here
    default:
        // code to execute when expression doesn't match any of the cases
        break;
}

Here's an example of how switch-case statement can be used in a class:

C#:
public class MyClass
{
    public void ProcessValue(int value)
    {
        switch (value)
        {
            case 1:
                Console.WriteLine("Value is 1");
                break;
            case 2:
                Console.WriteLine("Value is 2");
                break;
            case 3:
                Console.WriteLine("Value is 3");
                break;
            default:
                Console.WriteLine("Value is not 1, 2 or 3");
                break;
        }
    }
}

In the example above, the ProcessValue method takes an integer value as input and uses the switch-case statement to determine what to do based on the value. If the value is 1, 2 or 3, the method will output a message indicating that the value is 1, 2 or 3 respectively. If the value is not 1, 2 or 3, the method will output a message indicating that the value is not 1, 2 or 3.

I hope this helps you with your activity! Let me know if you have any further questions.
 
Baka makatulong din. Old yang binigay ni bot haha

C#:
public static Orientation ToOrientation(Direction direction) => direction switch
    {
        Direction.Up    => Orientation.North,
        Direction.Right => Orientation.East,
        Direction.Down  => Orientation.South,
        Direction.Left  => Orientation.West,
        _ => throw new ArgumentOutOfRangeException(nameof(direction), $"Not expected direction value: {direction}"),
    };

C#:
public readonly struct Point
{
    public Point(int x, int y) => (X, Y) = (x, y);
    
    public int X { get; }
    public int Y { get; }
}

static Point Transform(Point point) => point switch
{
    { X: 0, Y: 0 }                    => new Point(0, 0),
    { X: var x, Y: var y } when x < y => new Point(x + y, y),
    { X: var x, Y: var y } when x > y => new Point(x - y, y),
    { X: var x, Y: var y }            => new Point(2 * x, 2 * y),
};

You do not have permission to view the full content of this post. Log in or register now.
 
Back
Top