Why is my C # constructor not working with the method I'm trying to use?

I may have misunderstood how the constructors work, but anyway I'm trying to create an array and populate it in the constructor.

I have the following code -

class ClsDeck
{
    private string[] deck = new string[52];
    private string[] hand = new string[12];
    BuildDeck()
    {
        //lots of code assigning images to each individual element of the "deck" array.
    }

    //many other methods that need to be called by a form.
}

      

Visual Studio 2012 insists that the method has a return type. I just added "void" to the BuildDeck method and the error went away, but every example I saw in the constructor must have the same name as the class and it was the only method in the class.

+3


source to share


4 answers


It doesn't even compile. BuildDeck()

has no return type. Constructor names must match the class name (including case). Replace BuildDeck

with ClsDeck()

.



+8


source


By definition, a constructor is a method that 1.) has the same name as the class, and 2.) has no return value.

In the above example, "BuildDeck" is not a constructor ... it is a method and therefore must specify a return type (or "void" if it returns nothing).



If you want a constructor, rename "BuildDeck" to "ClsDeck".

+4


source


There is virtually no constructor for your class.

Make the following changes and your code will compile:

class ClsDeck
{
    private string[] deck = new string[52];
    private string[] hand = new string[12];

    public ClsDeck()
    {
        // Place your array initializations here.
    }

    private void BuildDeck()
    {
        //lots of code assigning images to each individual element of the "deck" array. }
        //many other methods that need to be called by a form.
    }
}

      

+3


source


It won't work or compile. To achieve what you want, you can have a constructor for ClsDeck

and callBuildDeck

class ClsDeck {
    private string[] deck = new string[52];
    private string[] hand = new string[12];
    ClsDeck() { //lots of code assigning images to each individual element of the "deck" array. }

        //many other methods that need to be called by a form.
        BuildDeck();
    }

    private void BuildDeck() {
        //Build your deck
    }
}

      

+2


source







All Articles