Trouble with struct

  • Thread starter Thread starter Phil Hunt
  • Start date Start date
P

Phil Hunt

I have a problem with a struct that has a function.
There is no problem with the assigning value to the individual data item.
But when I have a line that invoke a function (very simple), it won't
compile, saying "Use of unassigned local variable ___". If I instantiate
the struct using the "new" word, everything works. What could be the
problem. The construct works in some of my program, but not this particular
one.

Thanks.
 
The long answer is that there are alot of very subtle differences between
structures and classes.

Unless you understand what all of these are, your best bet is to always use
a class. Odds are, that a structure doesn't offer you any advantages, and in
fact may present some issues.

The short answer is, "Post some code".
 
I have a problem with a struct that has a function.
There is no problem with the assigning value to the individual data item.
But when I have a line that invoke a function (very simple), it won't
compile, saying "Use of unassigned local variable ___". If I instantiate
the struct using the "new" word, everything works. What could be the
problem. The construct works in some of my program, but not this particular
one.

You're trying to call a method before all of the fields have been
assigned, which you're not allowed to do.

For instance, with this struct:
struct Point
{
public int x;
public int y;

public void SayHi()
{
Console.WriteLine ("Hello");
}
}

This code is okay:
Point p;
p.x = 0;
p.y = 10;
p.SayHi();

But this code isn't:
Point p;
p.x = 0;
p.SayHi();

p doesn't count as being completely initialized, because its y field
hasn't been initialized.
 
Right on the nail. Thanks. The compiler is smart, but not smart enough to
tell the function does not need the un-initialized field.
 
Right on the nail. Thanks. The compiler is smart, but not smart enough to
tell the function does not need the un-initialized field.

And indeed in a general case it can't - suppose that your struct is in
a different assembly; the current version might not use the field, but
a future one might.

The current way of doing things keeps matters sane.

Jon
 
Back
Top