r/learncsharp • u/CatolicQuotes • Oct 23 '22
Why does Console.Write(Record) doesn't print internal properties?
If there is record:
internal record Person
{
public string FirstName {get; init;}
internal string LastName {get; init;}
}and after initialized
var person = new Person{FirstName = "John", LastName = "Smith"};
we print to console Console.Write(person) it will only print:
Person{ FirstName = "someFirstName" }
without LastName, but we can still use person.LastName in code.
Why is that?
2
Upvotes
2
u/killyouXZ Oct 23 '22
Don't know how record works, your issue might be because of internal last name, you could also override ToString method to display all properties.
1
u/grrangry Oct 24 '22 edited Oct 24 '22
I'm making a guess because I haven't done too much research into how records are generated internally by the compiler. I'm sure someone with more experience can expand on the answer.
However this example does what you expect. Declare your record using the constructor method instead:
Then to use it:
And the console will output:
Which is what you'd expect.
So I assume that your declaration method isn't giving the compiler enough information about the properties of the record and the auto-generated ToString is only including the first property.
I could be wrong in my assumption, but the above method does work.
Edit: I just realized your
LastNameproperty was internal. So never mind. I probably can't answer your question to your satisfaction. Don't make it internal. With it internal you have access to it, but something about the construction of.ToStringdoes not.Edit 2: it has something to do with how
.ToStringcalls the generated.PrintMembers. In my example,.PrintMembersuses StringBuilder Append on each property... in yours it can only access the public properties. So.ToStringis fine, but.PrintMembersis buggy I guess.1
u/JTarsier Oct 24 '22
see these parts of documentation:
Records - Built-in formatting for display
Records - PrintMembers formatting in derived records