Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is GetType() a method or a class?

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?

like image 787
EKanadily Avatar asked Jan 30 '13 08:01

EKanadily


4 Answers

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.

like image 135
Jobo Avatar answered Oct 04 '22 15:10

Jobo


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.

like image 30
O. R. Mapper Avatar answered Oct 04 '22 15:10

O. R. Mapper


Because GetType() returns an instance of an object, you can use the dot to access properties or methods of the object that it returns.

like image 29
Matthew Watson Avatar answered Oct 04 '22 14:10

Matthew Watson


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.

like image 30
booyaa Avatar answered Oct 04 '22 13:10

booyaa