-6

While going through a codebase, I ran into a statement similar to the following:

new Class().MemberFunction();

What is this statement actually doing? Is it calling the member function without creating an object of this class?

Mahesh Nepal
  • 1,385
  • 11
  • 16
  • It is the same as `Class myInstance = new Class(); myInstance.MemberFunction();`, except it does not use an variable. The `new` *creates* the object/instance; and in both cases the [member] method call is invoked upon *an expression that Evaluates to an Instance*. This is the same reason why `AMethodReturningAnObjectOfClassThatMightBeNewOrReused().MemberFunction()` "works": the member is invoked on an *expression* of the appropriate `Class`. – user2864740 Nov 01 '18 at 05:56
  • 1
    Possible duplicate of [Method-Chaining in C#](https://stackoverflow.com/questions/1119799/method-chaining-in-c-sharp) – Anas Alweish Nov 01 '18 at 06:09

2 Answers2

1

It is creating a new instance of Class - as you can clearly see the new Class() part of the code - the only thing that's not "usual" about it is that it doesn't store the reference to that instance, but just use it to call the MemberFunction();.

This means that whoever wanted to execute the MemberFunction() did not need to keep the reference to the specific instance (which in turn, might mean that the MemberFunction() should be converted to a static method, but there's not enough information to know for sure).

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0
  1. Create a new class ( because of 'new' )

  2. Launch MemberFunction() which you called

it means, it doesn't work what you actually wanted.

even static already creates class once.

Arphile
  • 841
  • 6
  • 18
  • 2
    "even static already creates class once." What? calling a static member guarantees type initialization, but most certainly does not create an instance of the type... – Zohar Peled Nov 01 '18 at 05:50