Reputation: 413
How does this work in this manner? I'm confused. Why am I able from the second method to call: this.Method1();
if Method1 has a return type that is not a void.
I thought that whenever a method has a return type different than void, you would always have to attribute it to a variable of that same return type when calling that method. For example:
int c = Method1();
Also, shouldn't SecondMethod require instantiation like (?!) int c = new Vendor().Method1()
.
public class Vendedor
{
public int MyMethod()
{
return 2;
}
public int SecondMethod()
{
this.MyMethod();
return 3;
}
}
Upvotes: 0
Views: 43
Reputation: 726479
If a method has a non-void return type, you have an option to use it in an expression, assignment or otherwise, or to use it in a statement.
Most often, you call such methods for their values; however, an option to call these methods for their side effects is offered by the language.
In case of your method, which has no side effects, disregarding the return value is almost certainly an error. As of this writing, C# does not offer a reliable facility to detect it, though.
As far as the second part of your question goes, instance methods are allowed to call other instance methods without specifying object instance explicitly. In other words,
int c = Method1();
is the same as
int c = this.Method1();
Upvotes: 1
Reputation: 9355
The first question - You are not obliged to use the return value of a method. Even if you would be obliged to use it, you could still be able to ignore it anyway like this:
int c = this.MyMethod();
return 3;
which makes no sense anyway.
The second question - Since SecondMethod
is not static
(it is an instance member), You are already inside an instance of a class and thus can call this.MyMethod();
If you would use int c = new Vendor().MyMethod()
as you have suggested, then it would be a new different instance, and not the current one. This, ofcourse, is up to the business logic you need.
Upvotes: 3