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

7

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, because I know languages like PHP, Python and JavaScript.

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

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

As I'm used to other languages, I'd like an explanation on this.

Sample 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 done twice.

What is the meaning of this "duplication" of method names?

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

    
asked by anonymous 28.05.2016 / 19:05

3 answers

8

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. It has little to do with polymorphism.

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

Another reason for the confusion is that there is also the operator overload . It is a different mechanism from what is being addressed here. It is a type of polymorphism and is usually used in object orientation.

Operation

This is a general feature of methods of all kinds, normal, virtual, static, constructors, no matter what technology or application you are using. That's why documentation usually provides more than one version of it.

In general the methods of the same name do something very similar and have the same goal. It is just a facilitator for the programmer to remember the many 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. What makes it difficult to name and even encourage bad names, to the point of using fazAlgo1() , faAlgo2() , etc.

The methods are disambiguated by your signature (the details are there in the link ), that is, by the parameter types. That's why the feature makes no sense in dynamically typed languages.

Each language has a specific mechanism for selecting which method is most appropriate. C # does not consider the type of return, it has language that it considers. The compiler decides which option of these methods to call depending on the type of each parameter. This choice is often called betterness (which fits best) and is extremely complex because of the type hierarchy.

Of course internally the name is modified to make the compiler easier. You can not have two methods with the same name. As it could no longer have, even in different classes, that also has its name modified internally. I already said this in some answers.

Example

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

calls the first one. To call the second would be:

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

In ASP.Net MVC it 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 done by the name and the data that is going together in an HTTP request. / p>

Look how many different constructors have the class String . All the same name (of course), but each one 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 documentation list that in addition to the name are types to differentiate them.

So in an inheritance or implementation of an interface you need 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 default value for the parameters, which makes the need for overhead much smaller. That is, if you just put a value in a parameter, you do not have to do that. It is usually only necessary in cases where there is a different logic between one method and another.

    
28.05.2016 / 19:12
6

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

Although the name is the same, as in its example SendCode , the signatures of the methods are different, with specific parameters in each declaration.

From the parameters entered in the method call the compiler can define which method to execute.

    
28.05.2016 / 19:12
4

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

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

I hope to have helped, hug.

    
28.05.2016 / 19:11