C
C#3mo ago
Weenie

In the simplest terms possible, what *is* a constructor?

Im so confused, and the w3schools article is no help :(
5 Replies
bebopper
bebopper3mo ago
According to GPT4, "A .NET C# constructor is a special kind of method in C# used to create and initialize objects from a class. When you create a new instance of a class, the constructor sets up the initial state of the object, like setting initial values for its properties or fields. Constructors have the same name as the class and do not have a return type, not even void." I couldn't have said it better myself.
Angius
Angius3mo ago
Construction is what gets called when you create a new instance of an object That's the long and short of it, basically
MODiX
MODiX3mo ago
Angius
REPL Result: Success
class Foo
{
public Foo(string name)
{
Console.WriteLine($"Hello from the constructor, {name}");
}
}

var f = new Foo("Bob");
class Foo
{
public Foo(string name)
{
Console.WriteLine($"Hello from the constructor, {name}");
}
}

var f = new Foo("Bob");
Console Output
Hello from the constructor, Bob
Hello from the constructor, Bob
Compile: 464.199ms | Execution: 31.657ms | React with ❌ to remove this embed.
Weenie
Weenie3mo ago
Why not just say "public string Foo;" instead of saying "public Foo(string name)?
SinFluxx
SinFluxx3mo ago
Because constructors don't have return types public string Foo would imply a method named Foo that returns a string whereas a constructor is always [optional access modifier] [name]([parameters])