none
ignoring else RRS feed

  • Question

  • can we write if and else if and not writing else , will it work or it will show warning or error

    if(condition)

    {

    }

    else if(condition)

    {

    }

    /* not writing else part*/

    Tuesday, June 4, 2019 7:31 AM

Answers

  • Hi abcdefgefdedfd,

    Thank you for posting here.

    In c#, we could use else if and ignore else, it works well.

    I make a simple code, you could have a look.

                Console.WriteLine("please input a number");
                int m = Convert.ToInt32(Console.ReadLine());
                if(m<35)
                {
                    Console.WriteLine("it is less than 35");
                }
                else if(m<100)
                {
                    Console.WriteLine("it is less than 100");
                }
                Console.ReadKey();

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, June 4, 2019 7:49 AM
    Moderator

All replies

  • Hi abcdefgefdedfd,

    Thank you for posting here.

    In c#, we could use else if and ignore else, it works well.

    I make a simple code, you could have a look.

                Console.WriteLine("please input a number");
                int m = Convert.ToInt32(Console.ReadLine());
                if(m<35)
                {
                    Console.WriteLine("it is less than 35");
                }
                else if(m<100)
                {
                    Console.WriteLine("it is less than 100");
                }
                Console.ReadKey();

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, June 4, 2019 7:49 AM
    Moderator
  • Yes, you can do this, it will just ignore this code as if it never existed if none of the conditions are met. 

    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int x = 5;
                if(x==7) { Console.WriteLine("Yes, We have 7"); }
                else if(x==10) { Console.WriteLine("Yess, we have 10"); }
            }
        }
    }

    Regards


    • Edited by ThisNewbie Tuesday, June 4, 2019 7:53 AM
    Tuesday, June 4, 2019 7:50 AM
  • Yes, it will work,  and you don't need the last 'else' 
    Tuesday, June 4, 2019 7:52 AM