Adrao
Adrao

Reputation: 510

Initialize Class without a variable

Lets say i have a class with a few methods inside. Usually i initialize it like this:

var myClassObj = new MyClass("Hello World");
myClassObj.SomeMethod();

I'm a little confused because I've seen examples where people just do this:

new MyClass("Hello World").SomeMethod();

Without using a variable, Now can someone help me understand why they do that? and what is the difference?

Upvotes: 0

Views: 456

Answers (4)

Matias Cicero
Matias Cicero

Reputation: 26301

There is no difference at all, except that you're saving yourself a line of code. Internally, a local instance variable is still being created.

The reason why you can do something like this

new MyClass("Hello World").SomeMethod();

is because the MyClass constructor is returning a new instance of the class, and therefore you can handle this return value as you may consider appropiate.

Upvotes: 0

Jan Barta
Jan Barta

Reputation: 460

In the first example, you save instance of MyClass to variable myClassObj and then call function.

In the second example, you create new instance without explicitly saving it and call method on it. The new instance is then "lost" after executing of method.

Upvotes: 1

Mritunjay
Mritunjay

Reputation: 25892

when you will say this

var myClassObj = new MyClass("Hello World");

you will get a referance to that object which you can use later sometime.

but this

new MyClass("Hello World").SomeMethod();

you can use this object only here. If you want to use this object after sometime you cann't.

Upvotes: 2

JAYBEkster
JAYBEkster

Reputation: 790

Mybe you don't need using the variable and you have to call a function only once. See the difference

new MyClass("Hello World").SomeMethod();

equals to:

var myClass = new MyClass("Hello World");
myClass.SomeMethod();
delete myClass;

Upvotes: -2

Related Questions