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

Asked

Viewed 1,496 times

7

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

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

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

As I am used to other languages, I would like an explanation about this.

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

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

This has something to do with polymorphism or something similar?

3 answers

7


Term

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

Maybe because override resemble " 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’s a different mechanism than what’s being dealt with here. It’s a kind of polymorphism and is used in object orientation.

Functioning

This is a general feature of all kinds of methods, normal, virtual, static, constructors, no matter what technology or application you are using. That’s why the 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’s just a facilitator for the programmer to remember the various possible ways and an IDE can help by showing his various signatures.

Languages that do not have this feature have to give a different name for each method that has different parameters. Which makes naming difficult and even encourages bad names, to the point of using fazAlgo1(), fazAlgo2(), etc..

The methods are disambiguated by your signing (the details are there on link), i.e., by the types of parameters. Therefore, the resource makes no sense in dynamically typed languages.

Each language has a specific mechanism to select which is the most appropriate method. C# does not consider the type of return, it has language that it considers (even the names of the parameters or other characteristics of the contract). 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 something extremely complex because of the hierarchy of types.

Of course, internally the name is modified to facilitate the compiler. You cannot have two methods with the same name. Just as I could no longer have, even in different classes, that also has its name modified internally. I have said this in some answers.

Example

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

calls the first. To call the second would be:

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

I put in the Github for future reference.

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

Look how many different builders have the class String. All the same name (of course), but each operates in a different way). The same goes for regular methods. See the list that has several duplicated names. But none with the same signature. Note in the documentation list that in addition to the name it contains the 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 resource default for the parameters, which makes the need for the overload much less. That is, if you just want to put a value in a parameter you don’t have to do it. It is usually necessary only in cases where there is a different logic between one method and another.

7

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

Although the name is the same, as in your 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 run.

4

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

Realize 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 have an error.

I hope I helped, hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.