Bronsoner
Bronsoner

Reputation: 147

c# Do I have to specify name for a new class instance?

I'm making a simple game in unity and have a small uncretainity you could help me with: do I have to name the new instance of a class? for example:

public class CreateCharacter : MonoBehaviour {

public string charname;

public CreateCharacter (string charname)
{
    this.charname = charname;
    //does all the stuff needed
}}

I want to run this from another script:

int e = data.Length - 1;
            if (e > 0)
            {
                new CreateCharacter(data[e]);
                e--;
            }

data is a string array and CreateCharacter will store the new Character object in a list of such objects, so I can accss it later. My question is: Do I have to write:

CreateCharacter SomeName = new ChreateCharacter

for the code to run? or is simple

new Class (constructor)

enough?

Upvotes: 1

Views: 146

Answers (4)

Green Falcon
Green Falcon

Reputation: 836

If you use

new Class (constructor)

it is anonymous object and it does the job. This king of object is used whenever the object is not referenced from other places of your code and its benefit is that you are not supposed to find an appropriate name for that.

Upvotes: 1

Kellen Stuart
Kellen Stuart

Reputation: 8933

It won't cause the program to die using without storing it.

new CreateCharacter(data[e]);

but yes, you want to store it so you can call methods on it like

CreateCharacter char = new CreateCharacter(string);

char.methodName();

Your other option is to put the code you are trying to execute in a static method because it seems that the code you are running in the constructor is not dependent on the instance of the class CreateCharacter.

Upvotes: 1

Heckman
Heckman

Reputation: 398

You are allowed to call the constructor by itself like you stated. However, do keep in mind that the newly created object will immediately fall out of scope and be deallocated after the constructor is done. So depending on what's included in "// does all the stuff needed", it could -potentially- crash your app (although it would be unlikely).

As stated in other answers, it is a best practice in both readability and functionality to assign the newly created object to a variable, even if only for the scope of that for loop.

Upvotes: 1

Matt Clark
Matt Clark

Reputation: 1171

While it is poor practice to new something and not toss it in a variable, that code WILL compile and run just fine. Additionally, is there a reason you have a class called CreateCharacter? Instead of a function that returns an actual character given the data?

Upvotes: 1

Related Questions