Types of Calling Methods C #

4

I have a question in the following case, do not refuse dates, I used just as an example:

Convert.ToDateTime("01/01/2016 00:00:00").ToShortDateString();

What is the origin of this method ToShortDateString() ?

Another example:

var blablabla = string.Copy("asd").Clone().ToString();

How can one method "call" another method, what's the name of it?

    
asked by anonymous 07.12.2016 / 18:12

2 answers

6

Imagine that we have a method that returns a String:

public string StringMarota()

I can call this method and throw the result into a variable:

var marota = StringMarota();

Every string has method ToString , right?

var manola = marota.ToString();

The point is that you are not calling one method in the other, you are calling a method in return from the previous method. Returning to our example:

var marota = StringMarota();
var manola = marota.ToString();

Can be reduced to:

var manola = StringMarota().ToString();

As long as each method has a return, you can chain the calls.

    
07.12.2016 / 18:28
3
  

How can one method "call" another method, what's the name of it?

You are reading the code in the wrong way. The correct thing would be to say that the result of one method is executing another method .

This code snippet

Convert.ToDateTime("01/01/2016 00:00:00").ToShortDateString();

Can be converted as follows

DateTime date = Convert.ToDateTime("01/01/2016 00:00:00");
string stringDate = date.ToShortDateString();

What happens in the first example is that you are accessing a method that is available on the return of the previously executed method. Since the return of the ToDateTime method is DateTime , you have access to all available methods of the DateTime instance.

TLDR;

Just for information title, something close to the quote "How a method can call another method" can be found more easily in javascript, where it is more common to find a function that returns another function. Still, the code looks a bit different from the example above

function soma(arg1){
   return function(arg2){
      return arg1 + arg2;
   }
}

soma(1)(2); //retorna 3
    
07.12.2016 / 18:27