error CS0165 and structs

J

John Aldrin

Hi,

I'm confused about when compiler error "CS0165: Use of unassigned
local variable" should be generated. If I have a struct w/public
fields the error is not generated when the new operator is not used.
If there are no public fields the error is generated. Does this make
sense?

Ex 1 Public Fields

public struct TstStruct
{
public int x;
public int y;

public int X
{
get { return x;}
set { x = value;}
}
public int Y
{
get { return y;}
set { Y = value;}
}
};


// No compile errors

static void TestStruct()
{
TstStruct tstStruct; // new operator not used

tstStruct.x = 100;
tstStruct.y = 200;

tstStruct.X = 100;
tstStruct.Y = 200;

int aValue = tstStruct.X;

}

Ex 2 No Public Fields

public struct TstStruct
{
private int x;
private int y;

public int X
{
get { return x;}
set { x = value;}
}
public int Y
{
get { return y;}
set { Y = value;}
}
};


// Yes compile errors

static void TestStruct()
{
TstStruct tstStruct;

tstStruct.X = 100; // Compile error here
tstStruct.Y = 200;

int aValue = tstStruct.X;

}

Thanx

jra
 
N

Nick Malik

makes perfect sense to me.

The compiler doesn't want to generate an error if there is a *Remote
Possibility* that your code is correct as coded. If you have public fields,
someone COULD create the object correctly and assign values to those fields
before any internal code is called (especially since your example doesn't
include a constructor).

On the other hand, if the fields are private, the compiler now *Knows* that
no outside code is initializing those fields... and therefore raises the
error. I suppose that you could say that the compiler should warn you in
the first case, but it doesn't. (Perhaps there's a flag somewhere that
tells it to... ;-o)

Both of your examples are bad code... the compiler can only be certain of
one of them.
Note that all error messages are specific to the class where the code is
declared.

Personally, I think the fact that you didn't call "new" in your static void
TestStruct() should probably have generated an error, but it doesn't. Alas,
the compiler didn't catch that you have a unassigned ref variable. no big
surprise there. Personally, I'm not used to compilers doing that much for
me anyway.

I hope this helps,
--- Nick
 

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

Top