473,805 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

?? Basic C# Language Questions ??

Hi all,

I have two questions I was hoping someone could answer regarding C#.

First, I noticed C# does not allow local readonly variables. For example,
the following is illegal:

void X() {
readonly int i = 1;
}

I know that for this simple example I could have used const but there are
times when you must use readonly. Why can't readonly variables be local?

My second question has to do with jagged arrays. The following construct is
legal:
int[] a1 = {1, 2, 3};

but this is not:
int[][] a2 = {{1, 2, 3}, {4, 5}};

The above declaration of a2 will generate two errors (both the same):
"Array initializers can only be used in a variable or field initializer. Try
using a new expression instead."

I'm obviously missing something here. To my (obviously incorrect) way of
thinking, a2 *IS* being initialized with a variable initializer.

If I change the above declaration to this:

int[][] a2 = { new int[] {1, 2, 3}, new int[] {4, 5}};

the errors goes away. Would someone be able to clarify this behavior,
please?

Thanks very much.
May 12 '07 #1
14 2046
For one thing, I don't see any reason why local variables, which are
never accessed by any external code, should be readonly. You can use
constants (equivalent of readonly). But what readonly really means is
that external code (e.g. if you're making a DLL library and someone
else is supposed to use it) cannot change this property, while you may
still be able to change the inner variable. It only applies to
properties, which are exposed to external codes.

Next, for any array the "proper" declaration is:
int[] a = new int[] { xxxxxxx ];
But C# makes it easier, by using the "less legal" version
int[] a = { xxxxxxx };
That makes it a shorthand notation.
But it doesn't apply to the inner brackets of the jagged arrays.
The notation you said to be illegal is valid for multidimensiona l
arrays, though.

Freiddie
http://fei.yuanbw.googlepages.com/
http://freiddy.blogspot.com/
http://scilearn.blogspot.com/

May 12 '07 #2
'readonly' variables can be initialized either in the declaration or in a
constructor, but nowhere else. How did you expect this to relate to local
variables?

In your array example, your first initializer is a 2-dimensional array
initializer. Your second try is appropriate for a jagged array since it is
an array of arrays.
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
Instant C++: converts C# or VB to C++/CLI
"Robin Bowning" wrote:
Hi all,

I have two questions I was hoping someone could answer regarding C#.

First, I noticed C# does not allow local readonly variables. For example,
the following is illegal:

void X() {
readonly int i = 1;
}

I know that for this simple example I could have used const but there are
times when you must use readonly. Why can't readonly variables be local?

My second question has to do with jagged arrays. The following construct is
legal:
int[] a1 = {1, 2, 3};

but this is not:
int[][] a2 = {{1, 2, 3}, {4, 5}};

The above declaration of a2 will generate two errors (both the same):
"Array initializers can only be used in a variable or field initializer. Try
using a new expression instead."

I'm obviously missing something here. To my (obviously incorrect) way of
thinking, a2 *IS* being initialized with a variable initializer.

If I change the above declaration to this:

int[][] a2 = { new int[] {1, 2, 3}, new int[] {4, 5}};

the errors goes away. Would someone be able to clarify this behavior,
please?

Thanks very much.
May 12 '07 #3
Below...
"Freiddie" <fe********@gma il.comwrote in message
news:11******** *************@l 77g2000hsb.goog legroups.com...
For one thing, I don't see any reason why local variables, which are
never accessed by any external code, should be readonly. You can use
constants (equivalent of readonly).
const is certainly not the equivalent of readonly. Sure, they're similar, to
a limited extent, but not at all the same. Try doing this:
const MyClass mc = new MyClass();

But what readonly really means is
that external code (e.g. if you're making a DLL library and someone
else is supposed to use it) cannot change this property, while you may
still be able to change the inner variable. It only applies to
properties, which are exposed to external codes.
"...what readonly really means..."? No -- you have described one possible
use of 'readonly'. What readonly means is that once a value is assigned it
cannot be re-assigned. That's all it "means". You have described one
possible intention of using 'readonly', but certainly not the only reason.
There's no sense in going into details as to *why* I want to make a local
readonly. It just seems that there's no good reason why I shouldn't be able
to.


Next, for any array the "proper" declaration is:
int[] a = new int[] { xxxxxxx ];
But C# makes it easier, by using the "less legal" version
int[] a = { xxxxxxx };
"Less legal"? There's nothing "less legal" about it.

That makes it a shorthand notation.
But it doesn't apply to the inner brackets of the jagged arrays.
The notation you said to be illegal is valid for multidimensiona l
arrays, though.
Yes, Thank you. I've discovered this myself. That's what I was asking about.
You basically re-phrased what I'd already stated.
May 12 '07 #4
"David Anton" <Da********@dis cussions.micros oft.comwrote in message
news:89******** *************** ***********@mic rosoft.com...
'readonly' variables can be initialized either in the declaration or in a
constructor, but nowhere else. How did you expect this to relate to local
variables?
Yes, I know this. But why? What's the rational? I can think of a couple good
reasons for having readonly locals but no good reasons *not* to allow them.
I already understand what is allowed/disallowed. I'm trying to get at the
rational.
In your array example, your first initializer is a 2-dimensional array
initializer. Your second try is appropriate for a jagged array since it
is
an array of arrays.
Yes, yes, yes... I know that....
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
Instant C++: converts C# or VB to C++/CLI
"Robin Bowning" wrote:
>Hi all,

I have two questions I was hoping someone could answer regarding C#.

First, I noticed C# does not allow local readonly variables. For example,
the following is illegal:

void X() {
readonly int i = 1;
}

I know that for this simple example I could have used const but there are
times when you must use readonly. Why can't readonly variables be local?

My second question has to do with jagged arrays. The following construct
is
legal:
int[] a1 = {1, 2, 3};

but this is not:
int[][] a2 = {{1, 2, 3}, {4, 5}};

The above declaration of a2 will generate two errors (both the same):
"Array initializers can only be used in a variable or field initializer.
Try
using a new expression instead."

I'm obviously missing something here. To my (obviously incorrect) way of
thinking, a2 *IS* being initialized with a variable initializer.

If I change the above declaration to this:

int[][] a2 = { new int[] {1, 2, 3}, new int[] {4, 5}};

the errors goes away. Would someone be able to clarify this behavior,
please?

Thanks very much.

May 12 '07 #5
Robin Bowning <rb******@yahoo .comwrote:

<snip>
There's no sense in going into details as to *why* I want to make a local
readonly. It just seems that there's no good reason why I shouldn't be able
to.
I disagree on that front. Language features need to justify themselves
for inclusion, as each one contributes (even slightly) to the
complexity of the language. For instance, would you expect to be able
to do this:

readonly int x;

if (someCondition)
{
x = 0;
}
else
{
x = 1;
}

? The compiler could guarantee exactly one assignment, but the simpler
approach would be to force assignment in the same statement as
declaration. This kind of thing would need to be addressed in the spec.
Not having the possibility at all keeps the spec simpler.

So, I think there *is* sense in saying why it would be a positive thing
to have. For what it's worth, it's available in Java, and aside from
the times where one has to use it for anonymous inner classes reasons,
I can't remember ever seeing it being used. If one keeps methods
appropriately short (e.g. easily fitting on a single page) then it
should be reasonably clear that it's not being reassigned.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 12 '07 #6
I see - you want to set a variable to something at run-time (so a constant
won't work), but don't want it modifiable later in the method after assigning
a value.
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
Instant C++: converts C# or VB to C++/CLI
"Robin Bowning" wrote:
"David Anton" <Da********@dis cussions.micros oft.comwrote in message
news:89******** *************** ***********@mic rosoft.com...
'readonly' variables can be initialized either in the declaration or in a
constructor, but nowhere else. How did you expect this to relate to local
variables?

Yes, I know this. But why? What's the rational? I can think of a couple good
reasons for having readonly locals but no good reasons *not* to allow them.
I already understand what is allowed/disallowed. I'm trying to get at the
rational.
In your array example, your first initializer is a 2-dimensional array
initializer. Your second try is appropriate for a jagged array since it
is
an array of arrays.

Yes, yes, yes... I know that....
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
Instant C++: converts C# or VB to C++/CLI
"Robin Bowning" wrote:
Hi all,

I have two questions I was hoping someone could answer regarding C#.

First, I noticed C# does not allow local readonly variables. For example,
the following is illegal:

void X() {
readonly int i = 1;
}

I know that for this simple example I could have used const but there are
times when you must use readonly. Why can't readonly variables be local?

My second question has to do with jagged arrays. The following construct
is
legal:
int[] a1 = {1, 2, 3};

but this is not:
int[][] a2 = {{1, 2, 3}, {4, 5}};

The above declaration of a2 will generate two errors (both the same):
"Array initializers can only be used in a variable or field initializer.
Try
using a new expression instead."

I'm obviously missing something here. To my (obviously incorrect) way of
thinking, a2 *IS* being initialized with a variable initializer.

If I change the above declaration to this:

int[][] a2 = { new int[] {1, 2, 3}, new int[] {4, 5}};

the errors goes away. Would someone be able to clarify this behavior,
please?

Thanks very much.


May 12 '07 #7
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** ************@ms news.microsoft. com...
Robin Bowning <rb******@yahoo .comwrote:

<snip>
>There's no sense in going into details as to *why* I want to make a local
readonly. It just seems that there's no good reason why I shouldn't be
able
to.

I disagree on that front. Language features need to justify themselves
for inclusion, as each one contributes (even slightly) to the
complexity of the language. For instance, would you expect to be able
to do this:

readonly int x;

if (someCondition)
{
x = 0;
}
else
{
x = 1;
}

? The compiler could guarantee exactly one assignment, but the simpler
approach would be to force assignment in the same statement as
declaration. This kind of thing would need to be addressed in the spec.
Not having the possibility at all keeps the spec simpler.

So, I think there *is* sense in saying why it would be a positive thing
to have. For what it's worth, it's available in Java, and aside from
the times where one has to use it for anonymous inner classes reasons,
I can't remember ever seeing it being used. If one keeps methods
appropriately short (e.g. easily fitting on a single page) then it
should be reasonably clear that it's not being reassigned.

Let me offer some (admittedly subjective) justification then for why I think
it would be a positive change to have local 'readonly's.

First, they provide a useful means to communicate intent. When I'm reading
someone's code and I see 'readonly' it tells me that the author intended
this variable to be immutable. Many of us try to use "meaningful variable
names" because their use facilitates understanding of code intent.
'readonly' locals would serve the exact same purpose.

Second, it could help in code correctness. If I declare a variable as
readonly and then I later attempt to change it, I've made an incorrect
assumption somewhere and the compiler will tell me -- either I should not
have declared the variable as 'readonly' or I may be changing the wrong
variable or my understanding of the problem may not be correct.

Thirdly (and let me offer this one with a grain of salt), 'readonly' locals
may allow better IL generation. John, you're right that Java allows an
equivalent qualifier (final) on local variables. Unless I'm mistaken,
declaring a variable as 'final' in Java allowed the Java JITter (Hotspot) to
generate more efficient code.

Now, I may be completely wrong about the third point or perhaps it's a point
that does not even apply to C#/CLR. Even so, I think the first two points
are still valid and are advantages we harvest if 'readonly' locals are
allowed. Whether the advantages of 'readonly' locals outweigh the added
complexity they bring to the spec is an open question.

My main motivation for the original post was to discover whether there was
some intrinsic technical issue that precluded their existence and from the
responses so far, it seems here is not.
May 12 '07 #8
Hi Robin,

I wonder if one couldn't create a value type that only allows itself to
be assigned to once? That wouldn't provide the syntax sugar you crave,
nor the compile-time notification of any transgression, nor any IL
optimization opportunities. But it would provide the runtime
functionality anyway, and the intent would show in the code by the type
you're declaring (e.g., ReadOnlyInt32).

--Bob

Robin Bowning wrote:
Hi all,

I have two questions I was hoping someone could answer regarding C#.

First, I noticed C# does not allow local readonly variables. For example,
the following is illegal:

void X() {
readonly int i = 1;
}

I know that for this simple example I could have used const but there are
times when you must use readonly. Why can't readonly variables be local?

My second question has to do with jagged arrays. The following construct is
legal:
int[] a1 = {1, 2, 3};

but this is not:
int[][] a2 = {{1, 2, 3}, {4, 5}};

The above declaration of a2 will generate two errors (both the same):
"Array initializers can only be used in a variable or field initializer. Try
using a new expression instead."

I'm obviously missing something here. To my (obviously incorrect) way of
thinking, a2 *IS* being initialized with a variable initializer.

If I change the above declaration to this:

int[][] a2 = { new int[] {1, 2, 3}, new int[] {4, 5}};

the errors goes away. Would someone be able to clarify this behavior,
please?

Thanks very much.

May 13 '07 #9
Bob Grommes <bo*@bobgrommes .comwrote:
I wonder if one couldn't create a value type that only allows itself to
be assigned to once? That wouldn't provide the syntax sugar you crave,
nor the compile-time notification of any transgression, nor any IL
optimization opportunities. But it would provide the runtime
functionality anyway, and the intent would show in the code by the type
you're declaring (e.g., ReadOnlyInt32).
No, because it's not the *value* which is assigned to - it's the
*variable*. You tend to be creating a new value each time (with value
types), not changing an old one.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 13 '07 #10

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

Similar topics

2
4246
by: AK | last post by:
I don't want any part of the previous discussion on Visual Basic versus Visual Basic.Net. My query is about using Visual Basic for Applications; and whether it is better to use Visual Basic 6 or Visual Basic.Net as a springboard for studying VBA. I use Office 2000 and would like to use VBA as a tool to customize it. I have zero programming experience. I would like to read through and work on the examples of a beginners
8
10707
by: Orange Free | last post by:
I want to create a program that will ask a user a series of questions and then generate a Microsoft Word document whose content is dictated by the answers. I am not a professional programmer, and I understand only a little about OO programming. Should I a) stick to -- *gasp* -- Visual Basic to accomplish my goal; b) use Python, with which I am somewhat familiar, and which I would prefer to use; or
4
2234
by: Ramesh | last post by:
hi, Let me ask some basic questions. Can anybody explain me about the following questions: 1. When we have to create sn key? Whenever we compiled Component we have to create or it is a one time process? 2. What information contained in sn key. I gone through that it is having public key. How it is using this key to intract with client. 3. When we have to run gacutil.exe file. Whenever we
21
1744
by: Philipp | last post by:
Hey, did anyone have a good paper about the opject orianteted concept? wishes
25
680
by: Jhon | last post by:
Hi every one, I got very basic question, here i go: Say i have 11001 11010 bits which are infact 10 bits. Now i want to address every bit so if it is zero i would add one and if it is one then i would be adding zero. Folks say it manchester coding. Please note that left hand side just accept a single bit for every operation.
18
2403
by: Ann Scharpf via AccessMonster.com | last post by:
I am not sure which would be the best place to post this question, so I'm posing it here with Access general questions. I have reached the point many times in Word and in Access where my ignorance of VBA is a real detriment to me. I saw some posts about VBA classes with a particular vendor and the poster was advised not to take the class because of the likelihood of an unskilled trainer. My question is, would taking a Visual Basic...
13
3042
by: usenet | last post by:
How and where can one find out about the basics of VB/Access2003 syntax? I am a died in the wool C/C++/Java Linux/Unix programmer and I am finding it difficult to understand the program format for accessing objects, controls, etc. in VB/Access2003. In particular where will I find explanations of:- Actions, Functions, Methods, Properties - I'm understand the
23
4347
by: TefJlives | last post by:
Hi all, I'm learning a bit about C, and I have a few questions. I'm not trying to insult C or anything with these questions, they're just honestly things I don't get. It seems like pointers to chars are just how you deal with strings, and pointers to pointers to char just give you arrays of strings. What is the advantage of this vs. languages with a string type?
4
3105
by: Chris Asaipillai | last post by:
Hi there My compay has a number of Visual Basic 6 applications which are front endeed onto either SQL Server or Microsoft Access databases. Now we are in process of planning to re-write these applications into Visual Basic.Net. My managers main thought is that Visual Basic 6 is (or has!) stopped being supported by Microsoft.
28
3610
by: Randy Reimers | last post by:
(Hope I'm posting this correctly, otherwise - sorry!, don't know what else to do) I wrote a set of programs "many" years ago, running in a type of basic, called "Thoroughbred Basic", a type of business basic. I need to re-write it, bring it kicking and screaming to run on Windows XP. This is for a video rental place, tracks movie and game rentals, customers, employee transactions, reservations, does reports,..... and on. I know some of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10614
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
10109
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9186
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...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5544
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
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3008
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.