In the simplest terms possible, what *is* a constructor?
Im so confused, and the w3schools article is no help :(
5 Replies
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.
Construction is what gets called when you create a new instance of an object
That's the long and short of it, basically
Angius
REPL Result: Success
Console Output
Compile: 464.199ms | Execution: 31.657ms | React with ❌ to remove this embed.
Why not just say "public string Foo;" instead of saying "public Foo(string name)?
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])