473,671 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unassigned variables Confusion

I understand that if I don't assign a *local* variable before I use it, the
compiler will generate a "Use of unassigned local variable" error. What I
don't get is why doesn't the compiler just implicitly assign a default value
to my unassigned variable?

At this point you are getting ready to reply to me and tell me that this is
just a way for the compiler to protect me from introducing a possible bug by
preventing me from forgetting to assign the value. The problem is that if
that was true, why doesn't it do the same thing for field level variables? I
mean, surely I could screw up there too right?

I have been scouring the web for a good answer and I have been unlucky in
finding a good response. Thank you for you time.
Nov 16 '05 #1
12 1985
Hi Rene,

Field level variables will be initialized to default values when the
instance is contructed. Since the compiler takes care of this, you don't have
to explicitly assign the values.

HTH,
Rakesh Rajan

"Rene" wrote:
I understand that if I don't assign a *local* variable before I use it, the
compiler will generate a "Use of unassigned local variable" error. What I
don't get is why doesn't the compiler just implicitly assign a default value
to my unassigned variable?

At this point you are getting ready to reply to me and tell me that this is
just a way for the compiler to protect me from introducing a possible bug by
preventing me from forgetting to assign the value. The problem is that if
that was true, why doesn't it do the same thing for field level variables? I
mean, surely I could screw up there too right?

I have been scouring the web for a good answer and I have been unlucky in
finding a good response. Thank you for you time.

Nov 16 '05 #2
So why doesn't the compiler do the same thing for the local variables?

"Rakesh Rajan" <Ra*********@di scussions.micro soft.com> wrote in message
news:D7******** *************** ***********@mic rosoft.com...
Hi Rene,

Field level variables will be initialized to default values when the
instance is contructed. Since the compiler takes care of this, you don't
have
to explicitly assign the values.

HTH,
Rakesh Rajan

"Rene" wrote:
I understand that if I don't assign a *local* variable before I use it,
the
compiler will generate a "Use of unassigned local variable" error. What I
don't get is why doesn't the compiler just implicitly assign a default
value
to my unassigned variable?

At this point you are getting ready to reply to me and tell me that this
is
just a way for the compiler to protect me from introducing a possible bug
by
preventing me from forgetting to assign the value. The problem is that if
that was true, why doesn't it do the same thing for field level
variables? I
mean, surely I could screw up there too right?

I have been scouring the web for a good answer and I have been unlucky in
finding a good response. Thank you for you time.

Nov 16 '05 #3
Hi Rene,

Look at it like this:
You declare a local variable only when you are going to make any practical
use of the value it contains.
If the compiler had been setting default values for local variables as well,
they will either be set to null (for classes) etc., which will surely throw
an error as soon as you try to access it's members.

Hence, to make sure that you yourself initialize the local var's, we have
this design.

HTH,
Rakesh Rajan

"Rene" wrote:
So why doesn't the compiler do the same thing for the local variables?

"Rakesh Rajan" <Ra*********@di scussions.micro soft.com> wrote in message
news:D7******** *************** ***********@mic rosoft.com...
Hi Rene,

Field level variables will be initialized to default values when the
instance is contructed. Since the compiler takes care of this, you don't
have
to explicitly assign the values.

HTH,
Rakesh Rajan

"Rene" wrote:
I understand that if I don't assign a *local* variable before I use it,
the
compiler will generate a "Use of unassigned local variable" error. What I
don't get is why doesn't the compiler just implicitly assign a default
value
to my unassigned variable?

At this point you are getting ready to reply to me and tell me that this
is
just a way for the compiler to protect me from introducing a possible bug
by
preventing me from forgetting to assign the value. The problem is that if
that was true, why doesn't it do the same thing for field level
variables? I
mean, surely I could screw up there too right?

I have been scouring the web for a good answer and I have been unlucky in
finding a good response. Thank you for you time.


Nov 16 '05 #4
In fact the compiler does already initialize local variables to 0 or null (see the .locals init in the IL). But the C# compiler is being extra cautious and requesting you be explicit to how you want them initialized. And yes, it is inconsistent with how it treats member variables.

However, for statics, for example, the IL produced if you use a static field initializer is different form if you don't and there are performance optimizations based on this. So I think in terms of member variables they decided to be consistent within instance and statics and keep a then strict view on locals making people explicitly initialize them. This was, of course, consistent with best practice from C++ (the grandfather of C#) where locals would be garbage unless you initialized them.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<66************ *************** *******@microso ft.com>

Hi Rene,

Look at it like this:
You declare a local variable only when you are going to make any practical
use of the value it contains.
If the compiler had been setting default values for local variables as well,
they will either be set to null (for classes) etc., which will surely throw
an error as soon as you try to access it's members.

Hence, to make sure that you yourself initialize the local var's, we have
this design.

HTH,
Rakesh Rajan

Nov 16 '05 #5
Rene <no****@nospam. nospam> wrote:
I understand that if I don't assign a *local* variable before I use it, the
compiler will generate a "Use of unassigned local variable" error. What I
don't get is why doesn't the compiler just implicitly assign a default value
to my unassigned variable?

At this point you are getting ready to reply to me and tell me that this is
just a way for the compiler to protect me from introducing a possible bug by
preventing me from forgetting to assign the value. The problem is that if
that was true, why doesn't it do the same thing for field level variables? I
mean, surely I could screw up there too right?


Yes, but you basically *can't* protect yourself against that. If you've
got two methods, one of which sets a variable and the other of which
returns it, how would you expect the compiler to know in what order
those methods are called by other classes?

It's not that the compiler is doing the wrong thing with local
variables - it's that it doesn't have enough information to do the
right thing with static/instance variables.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
Well, I am still unclear on the issue. The only reason why I would declare a
field level variable is because I also have intentions to use it, otherwise
why would I bother?

Having said that, the compiler should enforce the same rules as the one
found for the Local variables! I don't get it!!!
Look at it like this:
You declare a local variable only when you are going to make any practical
use of the value it contains.
If the compiler had been setting default values for local variables as
well,
they will either be set to null (for classes) etc., which will surely
throw
an error as soon as you try to access it's members.

Nov 16 '05 #7
Exactly...and because you are going to use it, it should be ensures that you
set a value to it before it is accessed.

public void MyMethod()
{
Class1 obj;
Console.WriteLi ne(obj.Property 1); // This would cause an error
}

HTH,
Rakesh Rajan

"Rene" wrote:
Well, I am still unclear on the issue. The only reason why I would declare a
field level variable is because I also have intentions to use it, otherwise
why would I bother?

Having said that, the compiler should enforce the same rules as the one
found for the Local variables! I don't get it!!!
Look at it like this:
You declare a local variable only when you are going to make any practical
use of the value it contains.
If the compiler had been setting default values for local variables as
well,
they will either be set to null (for classes) etc., which will surely
throw
an error as soon as you try to access it's members.


Nov 16 '05 #8
Ok, I get it now. If by some magical way the compiler could know that I
would be calling the "get" method first, the compiler could raise an error
to let me know that I am about to do something stupid and I should call the
"set" method first. Boy, I feel like such as dumb ass. (Jon, you definitely
have enlightened me several times now, how could I ever repay you??)

Thank you all.

PS: Richard, thanks for pointing out the ILDASM stuff. I will check it out
as soon as I get a chance.
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Rene <no****@nospam. nospam> wrote:
I understand that if I don't assign a *local* variable before I use it,
the
compiler will generate a "Use of unassigned local variable" error. What I
don't get is why doesn't the compiler just implicitly assign a default
value
to my unassigned variable?

At this point you are getting ready to reply to me and tell me that this
is
just a way for the compiler to protect me from introducing a possible bug
by
preventing me from forgetting to assign the value. The problem is that if
that was true, why doesn't it do the same thing for field level
variables? I
mean, surely I could screw up there too right?


Yes, but you basically *can't* protect yourself against that. If you've
got two methods, one of which sets a variable and the other of which
returns it, how would you expect the compiler to know in what order
those methods are called by other classes?

It's not that the compiler is doing the wrong thing with local
variables - it's that it doesn't have enough information to do the
right thing with static/instance variables.

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

Nov 16 '05 #9
Yes, but this is equally valid:

public void MyMethod()
{
Class1 obj = null;
Console.WriteLi ne(obj.Property 1);
}

And in fact the compiler will have already emitted the IL instruction to do the same as the first line of the method, so simply declaring the variable *could* be enough for everything to work in a defined way. The issue is why does the C# compiler force you to assign a *specific* value when it has already ensured that it will default to null (in this case).

To me the answer is that C# is all about the code being explicitly obvious by looking at it, not having to infer details from knowledge outside of what you are looking at. This is one of the benefits for example of have to use the ref keyword at a method call site as well as in the method definition (of course the other reason is that you can overload ref and non-ref versions of a method and it needs to be able to tell the difference in that case).

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<0E************ *************** *******@microso ft.com>

Exactly...and because you are going to use it, it should be ensures that you
set a value to it before it is accessed.

public void MyMethod()
{
Class1 obj;
Console.WriteLi ne(obj.Property 1); // This would cause an error
}

HTH,
Rakesh Rajan

Nov 16 '05 #10

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

Similar topics

10
19708
by: Chris LaJoie | last post by:
Our company has been developing a program in C# for some time now, and we haven't had any problems with it, but just last night something cropped up that has me, and everyone else, stumped. I have a struct that contains several different types of data. This struct is used throuout the program. Now, when I compile, I get 6 errors, all of them "Use of possibly unassigned field 'awayTime'" or "Use of possibly unassigned field 'intlTime'"....
3
3952
by: Mike P | last post by:
I keep getting the error 'Use of unassigned local variable' in my code, which I have used before and it works fine : SqlTransaction Trans1, Trans2; SqlConnection objConnectionDeactivateInvisilinkLNX, objConnectionDeactivateInvisilinkSQLSRVXwireless; SqlCommand objCommandDeactivateInvisilinkLNX, objCommandDeactivateInvisilinkSQLSRVXwireless;
3
6473
by: John Smith | last post by:
In the following (pseudo)code, why is it that C# returns an "unassigned local variable" error for nVar? It seems I have to declare the variable outside foo() for the error to dissapear. void foo() { int nVar = 0; SqlDataReader rdr = objCmd.ExecuteReader();
29
2237
by: Joseph Geretz | last post by:
Use of unassigned local variable 'fs' Please see where I've indicated where the compiler is flagging this error in the method below. fs is initialized in the first line in the try block, so why is it flagged as unassigned in the finally block? Thanks for your help! - Joe Geretz -
9
6187
by: tshad | last post by:
I am getting an error: Use of unassigned local variable 'postDateRow' But it is assigned. Here is the code: int payDateRow; int postDateRow;
22
8413
by: Laura T. | last post by:
In the following example, c# 2.0 compiler says that a3 and ret are used before assigned. as far as I can see, definite assignment is made. If I add finally { ret = true; a3 = "b3";
8
11143
by: Dom | last post by:
This is a little tricky, but I think the error I'm getting isn't valid. The compiler just doesn't know my logic. MyObject o; switch (IntVariable) { case 1: o = new MyObject() break;
0
8919
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
8821
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
8670
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
7439
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
6230
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
4225
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
4409
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2813
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
2
1810
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.