C
C#2w ago
Trapyy

✅ When to use each constructor?

public class InventorySlot(Item item, int quantity)
{
public Item Item { get; } = item;
public int Quantity { get; private set; } = quantity;
}
public class InventorySlot(Item item, int quantity)
{
public Item Item { get; } = item;
public int Quantity { get; private set; } = quantity;
}
or
public class InventorySlot
{
public Item Item { get; }
public int Quantity { get; private set; }

public InventorySlot(Item item, int quantity)
{
Item = item;
Quantity = quantity;
}
}
public class InventorySlot
{
public Item Item { get; }
public int Quantity { get; private set; }

public InventorySlot(Item item, int quantity)
{
Item = item;
Quantity = quantity;
}
}
7 Replies
Pobiega
Pobiega2w ago
These are functionally the same, its a matter of preference. The minor difference is that the top one (primary constructor) lets you use the item and quantity variables again, in which case they would get captured and if they are captured and exposed as private fields, they are sadly not readonly, which is why I personally don't use primary ctors for non-records
Trapyy
TrapyyOP2w ago
uh, idk if i understood it, what do you mean can be used again? if they are captured and exposed as private fields, they are sadly not readonly can you give an example of it being captured and exposed? idk what that is
Pobiega
Pobiega2w ago
1 sec
MODiX
MODiX2w ago
Pobiega
REPL Result: Success
var a = new PrimaryCtor(1, 2);
a.Print();

public class PrimaryCtor(int a, int b)
{
public int A { get; } = a;

public void Print()
{
Console.WriteLine($"A = {A}");
a += 5; // allowed, but I kinda hate this
Console.WriteLine($"A = {A}");
// A is unchanged, but a is changed.
// a shouldn't exist at this point, if you ask me.
}
}
var a = new PrimaryCtor(1, 2);
a.Print();

public class PrimaryCtor(int a, int b)
{
public int A { get; } = a;

public void Print()
{
Console.WriteLine($"A = {A}");
a += 5; // allowed, but I kinda hate this
Console.WriteLine($"A = {A}");
// A is unchanged, but a is changed.
// a shouldn't exist at this point, if you ask me.
}
}
Console Output
A = 1
A = 1
A = 1
A = 1
Compile: 571.455ms | Execution: 46.756ms | React with ❌ to remove this embed.
Pobiega
Pobiega2w ago
there you go A gets the value from a, as we intended but a still exists, and can be mutated and used
Trapyy
TrapyyOP2w ago
ohh got it, thank you!
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?