C
C#2w ago
Faker

✅ Is there a difference when we use { get; init; } vs { get; } ?

C#
public record Person
{
public required string FirstName { get; init; }
public required string LastName { get; init; }
};
C#
public record Person
{
public required string FirstName { get; init; }
public required string LastName { get; init; }
};
Hello guys, if I omit the init keyword here, would it make a difference? From what I've understood with or without the init keyword, we would still be able to "modify" the object during instantiation, no?
13 Replies
reflectronic
reflectronic2w ago
var p = new Person
{
FirstName = "Hello",
LastName = "World"
};
var p = new Person
{
FirstName = "Hello",
LastName = "World"
};
this code only works if they are init it does not work if they are only get
Faker
FakerOP2w ago
oh ok, would it have work if we would have use the constructor instead of the object initializer?
reflectronic
reflectronic2w ago
i don't understand what you mean
Faker
FakerOP2w ago
I mean, without the init, we would only have been able to do this:
C#

var p = new Person("John","Doe");
C#

var p = new Person("John","Doe");
?
reflectronic
reflectronic2w ago
well, you can't, since you didn't declare a constructor at all
Faker
FakerOP2w ago
Ah I see, my bad sorry Assume the constructor is there
reflectronic
reflectronic2w ago
then, yes, you would have to use it that's 'the old way', i suppose
Angius
Angius2w ago
init basically lets you use a setter but only once, during initialization
Faker
FakerOP2w ago
yep I see
Angius
Angius2w ago
Functionally,
class Person(string name)
{
public string Name { get; } = name;
}

var p = new Person("John");
class Person(string name)
{
public string Name { get; } = name;
}

var p = new Person("John");
and
class Person
{
public string Name { get; init; }
}

var p = new Person { Name = "John" };
class Person
{
public string Name { get; init; }
}

var p = new Person { Name = "John" };
are about the same
Faker
FakerOP2w ago
yeah, it's just syntax sugar?
Angius
Angius2w ago
Lets you use initializer syntax with similar guarantees a constructor can give you Especially paired with a required keyword
Faker
FakerOP2w ago
yep I see Thanks !

Did you find this page helpful?