Is it possible to hide the parameterless constructor from a user in C#?
I want to force them to always use the constructor with parameters
e.g. this Position struct
public struct Position { private readonly int _xposn; private readonly int _yposn; public int Xposn { get { return _xposn; } } public int Yposn { get { return _yposn; } } public Position(int xposn, int yposn) { _xposn = xposn; _yposn = yposn; } }
I only want users to be able to new up a Position by specifying the x and y coordinates.
However, the parameterless constructor is ALWAYS available.
I cannot make it private. Or even define it as public.
I have read this: Why can't I define a default constructor for a struct in .NET?
but it doesn't really help.
If this is not possible - what is the best way to detect if the Position I am being passed has values?
Explicitly checking each property field? Is there a slicker way?
A struct may declare a parameterless instance constructor. A parameterless instance constructor is valid for all struct kinds including struct , readonly struct , ref struct , and record struct .
Although the CLR allows it, C# does not allow structs to have a default parameter less constructor. The reason is that, for a value type, compilers by default neither generate a default constructor, nor do they generate a call to the default constructor.
C# does not allow a struct to declare a default, no-parameters, constructor. The reason for this constraint is to do with the fact that, unlike in C++, a C# struct is associated with value-type semantic and a value-type is not required to have a constructor.
The CLR allows value types to have parameterless constructors, but C# doesn't.
No, you can't do this. As you said, similar question has been asked before - and I thought the answer was fairly clear that you couldn't do it.
You can create a private parameterless constructor for a struct, but not in C#. However, even if you do that it doesn't really help - because you can easily work around it:
MyStruct[] tmp = new MyStruct[1]; MyStruct gotcha = tmp[0];
That will be the default value of MyStruct - the "all zeroes" value - without ever calling a constructor.
You could easily add a Validate method to your struct and call that each time you received one as a parameter, admittedly.
Nope can't hide it. Structs cannot redefine zero arg constructor, so therefore its visibility can't be redefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With