473,654 Members | 3,042 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inherited Readonly Members

I have a field in an abstract class marked readonly. However, when I attempt
to modify that field in the constructor of a class which inherits it, I get a
compile-time error stating that 'A readonly field cannot be assigned to
(except in a constructor or a variable initializer).' Any ideas would be
apreciated, though I was hoping I wouldn't have to use a property.
Reuben.
Nov 17 '05 #1
9 2347
It can only be changed in the containing classes constructor, or in its
variable initializer. Private (non readonly) field, protected set method
would do the same, yes?

Regards,

Tim Haughton

"Reuben" <Re****@discuss ions.microsoft. com> wrote in message
news:6B******** *************** ***********@mic rosoft.com...
I have a field in an abstract class marked readonly. However, when I attempt to modify that field in the constructor of a class which inherits it, I get a compile-time error stating that 'A readonly field cannot be assigned to
(except in a constructor or a variable initializer).' Any ideas would be
apreciated, though I was hoping I wouldn't have to use a property.
Reuben.

Nov 17 '05 #2
"Tim Haughton" <ti*********@gm ail.com> wrote in news:tmNye.7233 9$H46.63876
@fe03.news.easy news.com:
It can only be changed in the containing classes constructor, or in its
variable initializer. Private (non readonly) field, protected set method
would do the same, yes?


You dont need a set method, you can just access the field directly if you declare it protected.
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programmin g is an art form that fights back"

Empower ASP.NET with IntraWeb
http://www.atozed.com/IntraWeb/
Nov 17 '05 #3


Reuben wrote:
I have a field in an abstract class marked readonly. However, when I attempt
to modify that field in the constructor of a class which inherits it, I get a


readonly means that the member can only be assigned to in the
constructor (or by an initialization expression).

But, in your case you can pass it's value to the parent constructor:

class Foo {
readonly int x;
protected Foo(..., int x) { ...; }
}
class Bar: Foo {
public static int calculate_x(obj ect args) { ...; return 0; }
public Bar(..., object args): base(..., calculate_x(arg s)) { ...; }
}

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #4
Chad Z. Hower aka Kudzu <cp**@hower.org > wrote:
"Tim Haughton" <ti*********@gm ail.com> wrote in news:tmNye.7233 9$H46.63876
@fe03.news.easy news.com:
It can only be changed in the containing classes constructor, or in its
variable initializer. Private (non readonly) field, protected set method
would do the same, yes?


You dont need a set method, you can just access the field directly if
you declare it protected.


Yes, if you don't believe (as I do) that fields should pretty much
*always* be private, with protected properties allowing access to
derived classes :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
You can call the base constructor with a value and initialize it in the base
class.

for example:

public class One
{
private readonly int _number;
public One(int number)
{
_number = number;
}
}

public class Two : One
{
public Two(int number) : base(number)
{
}
}

Hope this helps...

Frisky

"Reuben" <Re****@discuss ions.microsoft. com> wrote in message
news:6B******** *************** ***********@mic rosoft.com...
I have a field in an abstract class marked readonly. However, when I
attempt
to modify that field in the constructor of a class which inherits it, I
get a
compile-time error stating that 'A readonly field cannot be assigned to
(except in a constructor or a variable initializer).' Any ideas would be
apreciated, though I was hoping I wouldn't have to use a property.
Reuben.

Nov 17 '05 #6
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in
news:MP******** *************** *@msnews.micros oft.com:
Yes, if you don't believe (as I do) that fields should pretty much
*always* be private, with protected properties allowing access to
derived classes :)


Thats not always a good method. There is a more common practice of making fields only private or
protected, and all pulbic interfaces as properties. Applying this a level higher though just adds
codes to descendants in many cases.

--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programmin g is an art form that fights back"

Get your ASP.NET in gear with IntraWeb!
http://www.atozed.com/IntraWeb/
Nov 17 '05 #7
Chad Z. Hower aka Kudzu <cp**@hower.org > wrote:
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in
news:MP******** *************** *@msnews.micros oft.com:
Yes, if you don't believe (as I do) that fields should pretty much
*always* be private, with protected properties allowing access to
derived classes :)


Thats not always a good method. There is a more common practice of
making fields only private or protected, and all pulbic interfaces as
properties. Applying this a level higher though just adds codes to
descendants in many cases.


Microsoft's guidelines disagree with you :)

http://msdn.microsoft.com/library/de...l=/library/en-
us/cpgenref/html/cpconfieldusage guidelines.asp

"Do not use instance fields that are public or protected (Public or
Protected in Visual Basic). If you avoid exposing fields directly to
the developer, classes can be versioned more easily because a field
cannot be changed to a property while maintaining binary
compatibility."

Basically, the exact same reasons for avoiding public fields apply to
protected fields in my view.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in news:MPG.1d3b4e 57c10c97ff98c44 4
@msnews.microso ft.com:
Microsoft's guidelines disagree with you :)
Its not the only one I disagree with. :) Guidelines are just that, guidelines.

In fact I dont use privates at all - I realize this is heresy to many but we do a lot of inheriting
within our own frameworks and too often I've inherited someone elses object and very few
developers understand when to make something private and when to make it protected - and those
that do rarely sit and think about each declaration. Too often things that are private should be
protected (Fields, methods, properties). If its all protected - it can be inherited from. If you dont
intend your class to be inherited from, seal it.
"Do not use instance fields that are public or protected (Public or
Protected in Visual Basic). If you avoid exposing fields directly to
the developer, classes can be versioned more easily because a field
cannot be changed to a property while maintaining binary
compatibility."


The part they dont state is that doing so in many cases adds significant overhead, and if the
developer really doesnt undersand what they are doing and blindly follows this then those
inheriting from their class will have real problems.

Such advice is fine for final classes, but if its intended to be inherited from its bad advice to be
followed as a rule.

If you look at type datasets, or troll around with reflector you will see that in some cases
Microsoft does not follow consistent guildelins themselves, and certainly when they do they
are not using the same ones they have published for others. I suspect that those that published
these guidelines are different and simply provided some basic starts and tips for others since
many users do not know where to start.
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programmin g is an art form that fights back"

Develop ASP.NET applications easier and in less time:
http://www.atozed.com/IntraWeb/
Nov 17 '05 #9
Chad Z. Hower aka Kudzu <cp**@hower.org > wrote:
Its not the only one I disagree with. :) Guidelines are just that, guidelines.

In fact I dont use privates at all - I realize this is heresy to many
but we do a lot of inheriting within our own frameworks and too often
I've inherited someone elses object and very few developers
understand when to make something private and when to make it
protected - and those that do rarely sit and think about each
declaration. Too often things that are private should be protected
(Fields, methods, properties). If its all protected - it can be
inherited from. If you dont intend your class to be inherited from,
seal it.
Indeed, and I'd argue that classes should be sealed by default just
like methods are non-virtual by default. I find that inheritance should
be used far less frequently than it tends to be.

Versioning makes a huge difference here - if you've got nothing
private, then you pretty much can't refactor anything without breaking
an existing version. I'd find that unnecessarily restrictive.
"Do not use instance fields that are public or protected (Public or
Protected in Visual Basic). If you avoid exposing fields directly to
the developer, classes can be versioned more easily because a field
cannot be changed to a property while maintaining binary
compatibility."


The part they dont state is that doing so in many cases adds
significant overhead, and if the developer really doesnt undersand
what they are doing and blindly follows this then those inheriting
from their class will have real problems.


In some cases it adds significant overhead, but I'd say that's pretty
rare.
Such advice is fine for final classes, but if its intended to be
inherited from its bad advice to be followed as a rule.

If you look at type datasets, or troll around with reflector you will
see that in some cases Microsoft does not follow consistent
guildelins themselves, and certainly when they do they are not using
the same ones they have published for others. I suspect that those
that published these guidelines are different and simply provided
some basic starts and tips for others since many users do not know
where to start.


While I'd agree with most of that, this is one of the guidelines I
would really encourage to be followed on almost every occasion. The
exception for me is for occasional nested classes which are purely
there to encapsulate some data, and serve no purpose outside their
enclosing type. In those cases, having made the type itself private, I
don't feel so bad about making the fields internal so I can reference
them directly. Nothing else will ever be able to use the fields outside
the enclosing class, and it's easy enough to refactor that later on -
without the potential for breaking any other classes.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
1833
by: Michi Henning | last post by:
Hi, I can't find a statement about this in the threading sections in the doc... Consider: class Class1 { Class1() { _val = 42;
5
3077
by: cody | last post by:
I know I can use ArrayList.ReadOnly() to create a readonly version of it, but how can I achive a similar thing with a generic collection of .NET 2.0?
1
2047
by: skootr | last post by:
I have a Public Interface defined in a class module. I also have a form that implements that interface After building the solution, I added an Inherited Form (inherited from the above-mentioned form) to the project via the IDE However, when I drop down the "(base class events)" list, I can't find the methods defined in the interface. I know the interface has been inherited because if I enter an "Implements" statement in the derived...
6
1761
by: Peter Oliphant | last post by:
I just discovered that the ImageList class can't be inherited. Why? What could go wrong? I can invision a case where someone would like to add, say, an ID field to an ImageList, possible so that the individual elements in an array of ImageList's could be identified by the ID, thereby allowing re-ordering the array without harm. A person could identify by index into the array, but that would not be preserved by re-ordering (and re-ordering...
2
2971
by: lovecreatesbeauty | last post by:
I'm disturbed on this question on a long time. I think if I finally get understand it with your kind help, I will get close to a excellent C++ programmer. And I only can rely on your expertise and help. I've read some books, but no book focuses on this. Don't you think it is a very important thing of C++ programming language? So your knowledge is of great benefit to others, especially me. 1. Which (How many) members will be created...
4
1939
by: asad.naeem | last post by:
hi to all this is the problem about inheritence. I have designed a form with some essential controls which are required for every form which will inherited from it. for example i have Button1 on parent form and this button is visible to me on inherited form. The problem is: I have written a click event of the button1 on both of the forms. tell me the way if i click the button on inherited form only parents' click event will be called and...
14
2625
by: lovecreatesbea... | last post by:
Could you tell me how many class members the C++ language synthesizes for a class type? Which members in a class aren't derived from parent classes? I have read the book The C++ Programming Language, but there isn't a detail and complete description on all the class members, aren't they important to class composing? Could you explain the special class behavior in detail? Thank you very much.
19
2226
by: jan.loucka | last post by:
Hi, We're building a mapping application and inside we're using open source dll called MapServer. This dll uses object model that has quite a few classes. In our app we however need to little bit modify come of the classes so they match our purpose better - mostly add a few methods etc. Example: Open source lib has classes Map and Layer defined. The relationship between them is one to many. We created our own versions (inherited) of Map...
2
1946
by: eggie5 | last post by:
Hi, I have a class Dog which derives from Animal. Suppose my instance of Dog is bulldog. bulldog has all the members of Animal plus Dog. How can copy just the members from Dog to a new Dog called boxer? Just get the Dog members from bulldog and leave out any inherited members from Animal. Dog bulldog=new Dog(); <-has inhereited members from Animal
0
8375
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8815
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8707
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7306
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4149
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4294
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2714
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1593
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.