hi
Just a few days ago I've started learning C#.
BTW - I hope I'm not breaking any forum rules by putting three questions inside a single thread, but I don't want to "spam" this forum by making too many threads.
1)
From the book:
A field initializer is part of the field declaration, and consists of an equals sign followed by an expression that evaluates to a value. The initialization value must be determinable at compile time.
But if initialization value must indeed be determined at compile time, then the following code would produce an error, due to the fact that here the initialization value can’t be known at compile time, since memory on the heap is only allocated at run-time:
class A
{
B b = new B(); // here value of b can't be known until run time
}
2)
The following quote talks about about the usefulness of auto-implemented properties:
Besides being convenient, auto-implemented properties allow you to easily insert a property where you might be tempted to declare a public field.
You might, however, be tempted to release a version of the code with a public field, and then in a later release change the field to a property. However, the semantics of a compiled variable and a compiled property are different. If, in a later release, you were to switch from a field to a property, any assemblies accessing that field in the first release would have to be recompiled to use the property. If you use a property in the first place, the client doesn’t have to be recompiled.
Say I created class X, the member of which is also a public instance field named A, and put this class into assembly. Now some third party writes a code that access this field A. Later I decide to replace public field A with public property called A ( of same type as field was ), so I rewrite and recompile my class.
Now client would still access this property using the same code as it used for accessing field A -->
void Main
{
...
X x = new X();
int i = x.A;
...
}
And since the client code remains unchanged, I don't see the need for recompiling it?
3) Why must the value of constant be determined at compile time rather than at run time, while read only field can be determined at run time?