1

Suppose i am having a class

Class ABC
 {
  public string Method1()
  {
   return "a";
  }
  public string Method2()
  {
   return "b";
  }
  public string Method3()
  {
   return "c";
  }
 }

and Now i am calling this methods in two ways like :

ABC obj=new ABC();
Response.Write(obj.Method1());
Response.Write(obj.Method2());

Another way

Response.Write(new ABC().Method1());
Response.Write(new ABC().Method2());

The output will be same for above two method .

Can some please help me understanding the difference between obj.Method1() and new ABC().Method1()

Thanks in Advance..

Gourav
  • 17
  • 3

2 Answers2

3

obj and new ABC() are separate instances. In your example the output is the same because there is no instance-level data to show.

Try this to see the difference:

Class ABC
 {

  public string Name = "default"; 

  public string Method1()
  {
   return "a";
  }
 }

then use the code below to show the difference with instance-level data:

ABC obj=new ABC();
obj.Name = "NewObject";
Response.Write(obj.Method1());
Response.Write(obj.Name);

Response.Write(new ABC().Method1());
Response.Write(new ABC().Name);
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • `new` keyword allocates memory. http://stackoverflow.com/questions/377178/how-does-the-standard-new-operator-work-in-c – Arush Kamboj Jul 11 '12 at 17:23
  • @ArushKamboj: Can you please explain memory difference in detail ? – Gourav Jul 11 '12 at 17:30
  • @D stanley : Thanks for your reply . Is there any other difference between them ? – Gourav Jul 11 '12 at 17:31
  • Every time you use `new` you are allocating memory for a new object. Saving that reference (e.g. in `obj`) keeps the same instance around instead of allocating new instances. Won't make much difference in this case since there's no data to store and the instances will be garbage collected (destroyed) after their last use. – D Stanley Jul 11 '12 at 17:32
  • 1
    @Gourav : No. `new ABC().Method();` is equivalent to `ABC temp = new ABC(); temp.Method();` – D Stanley Jul 11 '12 at 17:34
1

What @d-stanley is trying to say is that you allocate memory on creation that is is very valuable resource.

And the more complete answer is this: Classes created with some logic in mind. Although is perfectly workable Response.Write(new ABC().Method1()); but this is very short function and not as much useless... When you design class you implemented some logic boundary functionality and properties. For example FileStream has a inner property of Stream and make it accessible via various properties and you could set it in overloaded Open() method and destroy it in Dispose() method. And for example another class BinaryReader implements Stream also but threat it differently. From your logic you could implement all functions on single class - some MotherOfAllFunctions class the implements all the functions of FileStream and BinaryReader - but it's not a way of doing it.

Another point: In most of the cases some (or huge) ammount of memory is taken to initialize some internal logic of the class - for example SqlConnection class. Then you call Open() or any other method to call a database - there's some very powerful mechanics is thrown kick-in to support state machine initialization, managed-to-unmanagment calls and a lot of code could be executed.

Actually what you doing in any new SomeCLass().SomeMethod<int>(ref AnotherObject) is:

Response.Write( 
                 var tmpABC = new ABC();   // Constructor call . Executed always (may throw)
                 string result = tmpABC.Method1();  // Or whatever could be casted to `string`
                 tmpABC.Dispose();   // GC will kick-in and try to free memory

                 return result;
              );

As you see - this is the same code as if you have written it in this way. So what happens here is a lot of memory allocations and almost immediately all this valuable memory is thrown away. It makes more sense to initialize ABC() class and all it functionality power once and then use it everywhere so minimize memory over allocation. For example - it doesn't make any sense to open SqlConnection function in every function call in your DAL class the then immediately close it - better declare local variable and keep it alive - some fully initialized classes live as long as application thread process exist. So in case of this code style:

public class Program
{
    private static FileStream streamToLogFile = new FileStream(...);

    public int Main(string [] args)
    {
         new Run(new Form1(streamToLogFile));
     }
}

In this logic - there's no need to keep class Form1 and I created it inline but all the functions the need to access FileStream object (valuable resource !) will access the same instance that been initialized only once.

Alex F
  • 3,180
  • 2
  • 28
  • 40