Why is it possible to define two or more methods with the same name in the same class in C#?

I'm starting my studies in C # with ASP.NET MVC today. I'm still adapting with some things I'm not used to seeing as I know languages like PHP, Python and JavaScript.

I realized that in a code that has already come ready, when starting a project ASP.NET MVC with Razor, which some methods of Class AccountController.cs, for example, are declared twice.

I did not understand why it is possible to define a method with the same name twice.

Like me I am used to other languages, I would like an explanation about it.

Example of the code that is in my project:

  // GET: /Account/SendCode
    [AllowAnonymous]
    public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
    {
        var userId = await SignInManager.GetVerifiedUserIdAsync();
        if (userId == null)
        {
            return View("Error");
        }
        var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
        var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
        return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
    }

    //
    // POST: /Account/SendCode
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> SendCode(SendCodeViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View();
        }

        // Generate the token and send it
        if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
        {
            return View("Error");
        }
        return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
    }

That is, the declaration of SendCode is made twice.

What is the meaning of this" duplication " of the name of the methods?

Does this have anything to do with polymorphism or something similar?

Author: Maniero, 2016-05-28

3 answers

Term

This is called function overload (in English much better). It is quite common in statically typed languages. It exists in languages of various paradigms and is not a characteristic of object orientation, as many believe.

Maybe because override "resembles" overload people think it's the same thing. I know a lot of "experienced" programmer who mistakes this.

Another reason for the confusion is that there is also operator overload . It is a different mechanism than what is being dealt with here. It is a type of polymorphism and is often used in object orientation.

Operation

This is a general characteristic of methods of all kinds, normal, virtual, static, constructors, no matter what technology or application you are using. So the documentation usually provides more than one version of it.

In general the methods of the same name do something very similar and has the same purpose. It is just a facilitator for the programmer to remember the various possible ways and an IDE can help by showing the various signatures of it.

Languages that do not have this feature have to give a different name for each method that has different parameters. Which makes it difficult to name and even encourages bad names, going so far as to use fazAlgo1(), fazAlgo2(), etc.

Methods are disambiguated by their signature (details are there in the link), that is, by the types of the parameters. So the feature makes no sense in dynamically typed languages.

Each language has a specific mechanism to select which method is most suitable. C# does not consider the return type, it has language that considers (up to parameter names or other contract characteristics). The compiler decides which option of these methods to call depending on the type of each parameter. This choice is often called of betterness (which best fits) and is something extremely complex because of the hierarchy of types.

It is clear that internally the name is modified to facilitate the compiler. You can't have two methods with the same name. Just as it could no longer have, even in different classes, it also has its name modified internally. I've said that in some answers.

Example

SendCode("http://www.dominio.com", true)

Call the first. To call the second would be:

SendCode(new SendCodeViewModel()) //só pra exemplificar.

No ASP.NET MVC has extra importance because the method can be a controller action, so part of the route will determine which method to call, but this will be given by the name and the data that is going together in an HTTP request.

Look how many different constructors the class hasString. All the same name (of course), but each operates in a different way). the same goes for regular methods . See the list that has multiple duplicate names. But none with the same signature. Note in the list of documentation that in addition to the name there are types to differentiate them.

So in an inheritance or implementation of an interface it is necessary to be careful because the method to be inherited does not just have the same name, it has to have the exact signature that its superior.

Alternative

C # has the value feature default for the parameters, which makes the need for overhead much less. That is, if it is only to put a value in a parameter does not need to do this. Usually it is needed only in cases where there is a different logic between one method and another.

 7
Author: Maniero, 2020-10-27 15:28:28

This "duplication" is what we call method overhead. A characteristic present in object-oriented languages.

Although the name is the same, as in your example SendCode, the method signatures are different, with specific parameters in each statement.

From the parameters given in the method call the compiler can define which method to run.

 7
Author: Emerson JS, 2016-05-28 22:57:30

You can set the method with the same name if the method receives different parameter types.

Notice that the method SendCode(string returnUrl, bool rememberMe) receives two parameters, and the SendCode(SendCodeViewModel model) receives another type of parameter, so you can have more than one method with the same name, but if both methods received the same type of parameters, you would get an error.

Hope I helped, hug.

 4
Author: Robson Ferreira, 2016-05-28 17:47:08