Home > database >  How do i run my Code without using Main method in C# - Doing a Luhn Algorithm
How do i run my Code without using Main method in C# - Doing a Luhn Algorithm

Time:09-13

So I've been trying to make a Luhn-Algorithm what technically should now work but I searched a bit through the Internet and no one uses a Main method so neither do I, but my Questions or more like my Problem is how do I run the code without a Main Method?? Where do I put my Main method?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LuhnAlgorithm
{
    public static class Luhn
    {
            
            static bool IsValid(string number)       
            {
                if (string.IsNullOrEmpty(number)) return false;
                bool onSecondDigit = false;
                int count = 0;
                int sum = 0;
                for (int i = number.Length - 1; i >= 0; i--)
                {
                    char c = number[i];
                    if (!char.IsDigit(c))
                    {
                        if (c == ' ') continue;
                        return false;
                    }
                    int digit = c - '0';
                    if (onSecondDigit)
                    {
                        digit *= 2;
                        if (digit > 9) digit -= 9;
                    }
                    sum  = digit;
                    count  ;
                    onSecondDigit = !onSecondDigit;
                }
                return count > 1 && sum % 10 == 0;
            }
        }
    }

CodePudding user response:

You always need an entry point for your application which is the Main method of your program class. Since C#9 you can use top-level-statements in console applications where C# will add a class and Main method for you. So you don't have to implement it but technically it exists.

See https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements

You just implemented a class and most code examples don't do more because it is expected that you know how to write a simple C# application where you can use that class.

  •  Tags:  
  • c#
  • Related