When would you like to initialize a variable in a class, with the constructor or just declare it?

Asked 2 years ago, Updated 2 years ago, 38 views

We are developing C# and Java recently. I have a question. What is the best way to initialize a variable?

public class Dice
{
    private int topFace = 1;
    private Random myRand = new Random();

    public void Roll()
    {
       // ......
    }
}

Define it like this and initialize it at the same time

public class Dice
{
    private int topFace;
    private Random myRand;

    public Dice()
    {
        topFace = 1;
        myRand = new Random();
    }

    public void Roll()
    {
        // .....
    }
}

Which is the better way to initialize by creating a constructor? You want to code in a better way.

c# java

2022-09-21 14:16

1 Answers

My rule is:


2022-09-21 14:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.