Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why structs are used to encapsulate a string? #171

Closed
ppasieka opened this issue Oct 11, 2021 · 1 comment · Fixed by #179
Closed

Why structs are used to encapsulate a string? #171

ppasieka opened this issue Oct 11, 2021 · 1 comment · Fixed by #179
Labels
question Further information is requested

Comments

@ppasieka
Copy link

I see that the library is using structs to encapsulate strings. The types are public, so nobody will stop the consumers from calling the default constructor and, in consequence, entering a bad state.

Example from here: https://github.com/gregsdennis/json-everything/blob/master/JsonPointer/PointerSegment.cs

public struct PointerSegment : IEquatable<PointerSegment>
{
		/// <summary>
		/// Gets the source string.
		/// </summary>
		public string Source { get; private set; }
		
		public static PointerSegment Parse(string? source, bool uriFormatted)
		{
			if (source == null) throw new ArgumentNullException(nameof(source));
			/... rest of code

What is the benefit of using a struct instead of class here? The encapsulated string will end up on the heap anyway?

Classes would disallow the use of default constructor, which in consequence would enforce correctness

@ppasieka ppasieka added the question Further information is requested label Oct 11, 2021
@gregsdennis
Copy link
Owner

gregsdennis commented Oct 15, 2021

I'm not sure I have a good answer here. I was thinking along the lines of following in the footsteps of JsonElement, which is a struct. Not sure I thought through it enough.

I'll explore this and see what changes are easily supported.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants