Reputation: 169
I was just watching some videos on C# and I ran across something I did not understand. Lets say I have a class
class person
{
public string Name;
}
in my main code I place
new Person()
without declaring Person New =
Does it just create a reference of an object without a name on the Heap? What is the perpose of doing this?
Upvotes: 0
Views: 105
Reputation: 3589
The object will be created and HOPEFULLY garbage collected soon after since there is no reference to it. There is a caveat though. The constructor of this object can be arbitrarily complex. The compiler can't just optimize the statement away, because the constructor might be reflecting into another assembly, instantiating an HttpClient
and firing the missiles. It could potentially even register itself as a member of some other class, or in some collection via shared/global state.
One thing you can be sure of though: If you see lines in a codebase that only consist of creating an object and then not assigning or passing it along inline somewhere, you have a pretty bad design smell right there.
EDIT: Here's an example of some really crappy code that would result in the object sticking around "forever"
static class GlobalState
{
public static IList<object> GlobalStuff = new List<object>();
}
class Hacker
{
public Hacker()
{
GlobalState.GlobalStuff.Add(this);
}
public override string ToString()
{
return "hacker!!";
}
}
class Program
{
static void Main(string[] args)
{
new Hacker();
Console.WriteLine(GlobalState.GlobalStuff[0].ToString());
}
}
Upvotes: 2
Reputation: 29026
It Creates an object but not assigned to any variable as Bawa said in the previous answer. Here i would like to include few more, that will explain how can we confirm that it creates a new instance:
Let me add a constructor to the class ; and define a new static variable; That is for maintaining the instance number;
public static int instanceConst = 0;
class person
{
public string Name;
public person()
{
instanceConst++;
}
}
So that the instanceConst
will increased by 1
for each instance. Now we can check them as follows:
int personInstanceNumber = 0;
var instant1 = new person();
personInstanceNumber = instanceConst; // personInstanceNumber=1
var instant2 = new person();
personInstanceNumber = instanceConst;// personInstanceNumber=2
instant1 = new person();
new person();
personInstanceNumber = instanceConst; // personInstanceNumber=4
That means an instance is created but, it is not used;
Upvotes: 3
Reputation: 876
it creates an object for you without a reference variable name. you create object without a reference variable name when you dont want to use that same object ever again.
by ever again - i mean if you are not going to use that object anywhere else in the program.
Upvotes: 7