Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the number of a month in C# function

Tags:

c#

I want to return the number of a month and i made a function but it always returns 0

this is my code:

public int getNrMonth(String s)
    {
        int nr=0;
        if (s.Equals("January"))
            nr = 1
        if (s.Equals("February"))
            nr = 2;
        return nr;


    }

Could someone tell me wath is wrong please? I'm beginner!

like image 302
john Avatar asked May 19 '10 17:05

john


People also ask

Is Triangle program in C?

Algorithm. Step 1: Declare three sides of triangle. Step 2: Enter three sides at run time. Step 3: If side1 == side2 && side2 == side3 Go to step 6 Step 4: If side1 == side2 || side2 == side3 || side3 == side1 Go to Step 7 Step 5: Else Go to step 8 Step 6: Print the triangle is equilateral.


3 Answers

Why wouldn't you use the built in function:

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

Here is an example on use:

How to parse a month name (string) to an integer for comparison in C#?

like image 109
Avitus Avatar answered Nov 11 '22 03:11

Avitus


It'd be better to do it like this:

switch (s.Trim().ToUpper())
{
    case "JANUARY": return 1;
    case "FEBRUARY": return 2;
    // etc.
}

return 0;

Reasons:

  1. switch is optimized to begin with (small point, but worth mentioning).
  2. Once you have the value, all the remaining if checks are pointless.
  3. Assuming you want "january" and "January" and " January " and "jaNuarY" all to return 1, the Trim() and ToUpper() calls will take care of that.
like image 37
Dan Tao Avatar answered Nov 11 '22 03:11

Dan Tao


OK, you're a beginner, but you still have tools at your disposal. Set a breakpoint and step through in the debugger. Take a look at the value of s and nr as you do. Notice which if statements execute the nr = part and which you don't. Then you will understand. As it stands I don't think you pasted your real code in, because your question is missing a semi colon and might not even compile.

like image 29
Kate Gregory Avatar answered Nov 11 '22 02:11

Kate Gregory