Why Am I Getting a Constructor Error in C# Even When I Pass Arguments?

0
3
Asked By TechWhiz42 On

I'm having a bit of trouble with a C# constructor error that says it takes zero arguments, but I'm pretty sure I'm passing in four arguments correctly. Here's the constructor I've defined:

```csharp
public Item(AbilityKey abilityKey, Inventory.ItemFlag flags = (Inventory.ItemFlag)0, int originalOwner = 0, int replenishCooldown = 0)
{
this.SetAbilityKey(abilityKey);
this.flags = flags;
this.originalOwner = originalOwner;
this.replenishCooldown = replenishCooldown;
}
```

Where I'm encountering the issue is here:

```csharp
inventory.Items.Add(new Inventory.Item
{
abilityKey = AbilityKey.TorchLight,
flags = 0,
originalOwner = -1,
replenishCooldown = 0,
}
```

It gives me the error "Inventory.Item does not contain a constructor that takes 0 arguments." What am I missing? Thanks for any help!

3 Answers

Answered By DevNinja99 On

Yeah, those curly brackets are making it look like you're trying to use an empty constructor, not actually passing the constructor parameters. Just switch to using the parentheses for your constructor, and you'll be good to go!

TechWhiz42 -

Thank you!

Answered By CodeCracker77 On

You're actually using an object initializer here, which isn't calling the constructor the way you think. Instead of `new Inventory.Item {...}`, use `new Inventory.Item(AbilityKey.TorchLight, 0, -1, 0);`. This way, you're actually invoking the constructor with the required parameters rather than trying to use the curly braces, which just sets properties separately.

TechWhiz42 -

Thank you!

Answered By SyntaxSleuth On

You're right on track with thinking about the parameters! The lack of parentheses means you're not going through the constructor. You can either define a parameterless constructor or just create your object the right way like this: `new Inventory.Item(AbilityKey.TorchLight, 0, -1, 0)`.

TechWhiz42 -

Thank you!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.