Declaring readonly public property in C#

J

Jon Maz

Hi,

Quick & easy one - why does this code give an error?


=====
CODE
=====

private int numberOfPages;

public readonly int NumberOfPages
{
get { return numberOfPages; }
}


======
ERROR
======

The modifier 'readonly' is not valid for this item (pointing to line
"public readonly int NumberOfPages").


TIA,

JON
 
J

Jon Skeet [C# MVP]

Jon Maz said:
Quick & easy one - why does this code give an error?

Because that's not how you make a property read-only. You make it read-
only by only giving it a get {...} accessor, not a set {...} accessor.
 
J

Jon Maz

Hi Jon,

I thought of that, but it just looked kind of wrong (VB.Net habits, I
suppose), and the IDE gave me some kind of disapproving comment...

Still, I am now reassured.

Thanks!

JON
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top