I came across this code :
int myInt = 0;
textBox1.Text = myInt.GetType().Name;
According to the .NET documentation, GetType() is a method, not a class.
My question is that how am I able to use the dot with a method, like this GetType().Name
?
A method can return a class instance, here it´s an instance of the class Type
. On this object you can access properties, other methods, etc.
Your code could be written as this:
int myInt = 0;
Type t = myInt.GetType();
textBox1.Text = t.Name;
Maybe it´s easier to understand that way.
Edit:
A method call like GetType()
executes the method, and everything you do after the .
applies to the return value of the method, in this case an object of type Type
.
GetType()
is a method that returns an instance of a class (in this case, an instance of the Type
class.
Members of that returned instance of Type
are accessed via the dot syntax.
Because GetType()
returns an instance of an object, you can use the dot to access properties or methods of the object that it returns.
The term is commonly know as chaining (certainly in C# and JavaScript) or fluent interface.
So as the other two answers suggested, you are return an instance and executing the methods that are part of that class.
To quote wikipedia:
In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide for more readable code.
A fluent interface is normally implemented by using method chaining to relay the instruction > context of a subsequent call (but a fluent interface entails more than just method chaining). Generally, the context is defined through the return value of a called method self-referential, where the new context is equivalent to the last context terminated through the return of a void context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With