Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make readonly (not just private) automatic properties?

Automatic properties let me replace this code:

private MyType myProperty;
public MyType MyProperty
{
    get { return myPropertyField; }
}

with this code:

public MyType MyProperty { get; private set; }

with a few changes here and there - but is there a way to replace this code:

private readonly MyType myProperty;
public MyType MyProperty
{
    get { return myPropertyField; }
}

with something similar?

like image 273
Simon Avatar asked Oct 08 '09 09:10

Simon


People also ask

Can readonly be modified?

You can only change the value of a readonly variable at the constructor level of the same class. An Excerpt about readonly is : A readonly field can only be set upon field initialization or in a constructor.

What are the properties of read-only?

A class property declared read-only is only allowed to be initialized once, and further changes to the property is not allowed. Read-only class properties are declared with the readonly keyword* in a typed property.

Can a property be readonly C#?

C# ReadOnly Property FeaturesIn c#, we can create the Read-only fields using readonly keyword. In c#, you can initialize the readonly fields either at the declaration or in a constructor. The readonly field values will evaluate during the run time in c#.


1 Answers

Indeed, there is no way to do this at present.

We realize that in C# 3 we produced a bit of a philosophical oxymoron. The design of LINQ is heavily steeped in traditional immutable functional style of programming -- execution is deferred, queries are represented by immutable monads, expression trees are immutable, and so on.

And yet at the same time object initializers, collection initializers and auto props all encourage a traditional mutable-component-based style of programming. It seems like we are pushing in both directions -- which is indicative of the nature of C#; it's a pragmatic programming language that supports many different styles of programming.

However, since we are all big fans of the immutable style of programming, and since we believe that this style will pay dividends in making it easier to ensure the correctness of massively multithreaded applications in future ubiquitous multi-core architectures, we're definitely interested in figuring out some way to tame the mutability we've introduced. Readonly autoprops are one obvious way to do that; a small step, but a good one.

That all said, we have not even shipped C# 4 yet, and have not announced that there will be any new language features after that. You should treat all my musings about hypothetical features of unannounced products as "for entertainment purposes only" speculations, not as promises or announcements.

like image 62
Eric Lippert Avatar answered Nov 15 '22 18:11

Eric Lippert