473,804 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Implicitly typed local variables, why local only?

Could someone tell me why is not possible to have Implicitly typed* field
level* variables? For example, why won't the following code compile?

class Program
{
var myString = "abc";

static void Main(string[] args)
{
}
}

If I try to compile this I get the following error: "The contextual keyword
'var' may only appear within a local variable declaration".

Why do I get that error? I mean, if I move the variable declaration inside
the "Main" method things compile perfectly fine so it's obvious that the
compiler is able to infer the type but why does it only work inside a
method?

Thanks.

Oct 8 '08 #1
3 4225
Rene wrote:
Could someone tell me why is not possible to have Implicitly typed*
field level* variables? For example, why won't the following code compile?

class Program
{
var myString = "abc";

static void Main(string[] args)
{
}
}

If I try to compile this I get the following error: "The contextual
keyword 'var' may only appear within a local variable declaration".

Why do I get that error? I mean, if I move the variable declaration
inside the "Main" method things compile perfectly fine so it's obvious
that the compiler is able to infer the type but why does it only work
inside a method?
I would definitely not like a public field of type var - documentation
of it would be let us call it slightly frustrating.

:-)

Arne
Oct 8 '08 #2
Rene wrote:
Could someone tell me why is not possible to have Implicitly typed*
field level* variables? For example, why won't the following code compile?

class Program
{
var myString = "abc";

static void Main(string[] args)
{
}
}

If I try to compile this I get the following error: "The contextual
keyword 'var' may only appear within a local variable declaration".

Why do I get that error? I mean, if I move the variable declaration
inside the "Main" method things compile perfectly fine so it's obvious
that the compiler is able to infer the type but why does it only work
inside a method?

Thanks.
The var keyword is mainly intended for use with anonymous classes, and
an anonymous class is limited to the method where it's created.

I think that the var keyword was limited to methods simply to reduce the
misuse of it. You should not use the var keyword for something as
trivial as declaring a string variable, as the code doesn't get more
readable from it.

In some cases it's useful, for example, instead of:

Dictionary<stri ng, Dictionary<stri ng, List<int>>tree = new
Dictionary<stri ng, Dictionary<stri ng, List<int>>>();

you can use:

var tree = new Dictionary<stri ng, Dictionary<stri ng, List<int>>>();

Other uses may reduce the readability, for example:

var x = 42.0;

You need to know a bit about how literal values work, to realise whether
the type of the variable becomes a byte, short, int, long, float, double
or decimal.

--
Göran Andersson
_____
http://www.guffa.com
Oct 8 '08 #3
On Oct 8, 2:53*am, "Rene" <a...@b.comwrot e:
Could someone tell me why is not possible to have Implicitly typed* field
level* variables? For example, why won't the following code compile?
All of this is IMO:

There's no technical reason why it couldn't be done, but there's a big
difference between local variables and member variables, as all of the
uses of local variables are in the (hopefully short) piece of code
from their declaration to the end of their scope. In other words, you
have all of the context available at the same place. That makes it
less of a problem for it to be not-necessarily-absolutely-obvious what
the type is - you can emphasize the "what the code does" rather than
"here are the details of how it accomplishes it". The type of a member
variable is a bit more important, and it's harder to clearly see all
of its uses in the same place.

Jon
Oct 8 '08 #4

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

Similar topics

176
8209
by: Thomas Reichelt | last post by:
Moin, short question: is there any language combining the syntax, flexibility and great programming experience of Python with static typing? Is there a project to add static typing to Python? Thank you, -- greetz tom
2
3324
by: |-|erc | last post by:
OK, here's the start of the index file I'm working on and its used for every page like so index.php?action=register index.php?action=logout etc. <?php define ('IN_SITE', 1 ); define ('LOGGED_IN', FALSE );
3
14976
by: Anita C | last post by:
I have the foll. code to update the value of an attribute: xmlDocument.Load("abc.xml"); XmlAttribute xmlAttrib = xmlDocument.SelectSingleNode(root/web/theme/@desc); xmlAttrib.Value = ddDes.SelectedItem.ToString(); xmlDocument.Save("abc.xml"); However, I get the foll. error: Cannot implicitly convert type 'System.Xml.XmlNode' to 'System.Xml.XmlAttribute'
25
6215
by: Steve Jorgensen | last post by:
Yup, Steve's full of tips, but hey, it makes him feel important, right? Ok, here goes. I've been trying to improve encapsulation by putting code in the same object as the stuff it affects, so I rarely refer to a subform ir parent form's controls or records from the other form. Instead, I call a procedure in that form that does the job. That's all fine and good, and nothing at all revolutionary, but it leaves one with an annoying...
5
2422
by: masood.iqbal | last post by:
My simplistic mind tells me that having local variables within looping constructs is a bad idea. The reason is that these variables are created during the beginning of an iteration and deleted at the end of the iteration. Kindly note that I am not talking about dynamically allocating memory within a loop, which is a perfectly valid operation (albeit with a chance of resulting in a memory leak, unless we are careful). The most common...
9
2211
by: Stefan Turalski \(stic\) | last post by:
Hi, I done sth like this: for(int i=0; i<10; i++) {...} and after this local declaration of i variable I try to inicialize int i=0;
22
27901
by: Christoph Boget | last post by:
I am getting an error (a few among many) for the following lines of code: retval.BrokerName = (( curRow == System.DBNull.Value ) ? SqlString.Null : (string)curRow ); retval.BrokerGroupId = (( curRow == System.DBNull.Value ) ? SqlInt32.Null : (int)curRow ); The errors are (in turn):
20
5990
by: Dennis | last post by:
I use the following code for a strongly typed arraylist and it works great. However, I was wondering if this is the proper way to do it. I realize that if I want to implement sorting of the arraylist then I have to handle this with a sort method that uses comparer. I can reference the properties of the Arraylist directly such as dim mylist as new FrameList mylist.Add(new FrameStructure) mylist(0).first = "blabla..." mylist(0).second...
55
6274
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
0
9715
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
9595
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
10600
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...
1
10354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10097
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
9175
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
7642
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
6867
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
5535
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...

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.