Proposal: Readonly methods that can only be called by constructors #3021
Replies: 5 comments
-
a readonly method already had a different meaning, all you would need a different keyword |
Beta Was this translation helpful? Give feedback.
-
Not without some kind of changes to the runtime. An assembly that writes to a readonly field outside of a constructor of that class is considered unverifiable. |
Beta Was this translation helpful? Give feedback.
-
see initonly |
Beta Was this translation helpful? Give feedback.
-
Rather than i.e. I really feel that this should work: public class Service
{
private readonly string _connectionString;
public Service()
{
_connectionString = GetConnectionString();
SetConnectionString();
string GetConnectionString()
{
return _connectionString;
}
void SetConnectionString()
{
_connectionString = ""; // This should work
}
}
} I don't know why it doesn't. It could be anything from "We just never implemented it" to "It's not technically possible / feasible". One of the others peeps here will be able to help with that one. |
Beta Was this translation helpful? Give feedback.
-
@Richiban That still wouldn't allow for reuse of those local functions though. For example, if you had another constructor taking a parameter (ie. bool isTestDb), you wouldn't be able to call that local function defined in the default constructor. Having a readonly-safe method (like an extension to the constructor), would help in code reuse. Obviously there are other ways to set |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
If I have a
readonly
field in my class, this has to be set by the class or the constructor. If I try changing this readonly field from a method called by the constructor, this gives an error. This is expected, since the private method can be called outside of the constructor, and we don't want to modify the readonly value from somewhere outside of the constructor.Is there a way to mark a method as
readonly
, meaning that a method may only be called from a constructor? Like so:This example is pretty simplistic and focused on readonly fields, but there could be a lot of bloat going into constructors, and refactoring this out to other methods (only callable by the constructor) would be ideal in those situations.
Beta Was this translation helpful? Give feedback.
All reactions