Field is never assigned to, and will always have its default value

G

Guest

private struct MySTRUCT
{
public IntPtr hwndMyObj;
public Int32 idMyObj;
public Int32 MyCode;
}
In Vb.Net 2005 code above, I am getting a warning message
"MyProj.MyClass.MySTRUCT.hwndMyObj is never assigned to,and will always have
its default value."

The same message for idMyObj and MyCode. How do I resolve it?
 
S

Stoitcho Goutsev \(100\)

Shayaan,

That is because you are using public fileds. the comiler always complains
about public or internal unasigned fileds.

Wrap them in properties; it will make the compiler happy.


struct MySTRUCT
{
private IntPtr hwndMyObj;
private Int32 myCode;
private Int32 idMyObj;

public IntPtr HwndMyObj
{
get { return hwndMyObj; }
set { hwndMyObj = value; }
}

public Int32 IdMyObj
{
get { return idMyObj; }
set { idMyObj = value; }
}

public Int32 MyCode
{
get { return myCode; }
set { myCode = value; }
}

}
 
G

Guest

Stoitcho,
Now I get the following errors on lines marked with 1, 2 and 3

1. The type 'MyProj.MyClass.MySTRUCT' already contains a definition for
'HwndMyObj'
2. The type 'MyProj.MyClass.MySTRUCT' already contains a definition for
'IdMyObj'
3. The type 'MyProj.MyClass.MySTRUCT' already contains a definition for
'MyCode'

struct MySTRUCT
{
private IntPtr hwndMyObj;
private Int32 myCode;
private Int32 idMyObj;

1. public IntPtr HwndMyObj
{
get { return hwndMyObj; }
set { hwndMyObj = value; }
}

2. public Int32 IdMyObj
{
get { return idMyObj; }
set { idMyObj = value; }
}

3. public Int32 MyCode
{
get { return myCode; }
set { myCode = value; }
}

}
 
C

Christof Nordiek

The code compiles fine on my machine (though i had to add using System;

from the error messages i suppose that you defined
private IntPtr HwndMyObj;
instead of
private IntPtr hwndMyObj;

look at the capital vs. small 'h' in th identifier.

convention is:
public properties beginn with capital letters.
private fields begin with small letters.
 
S

Stoitcho Goutsev \(100\)

Shayaan,

Make sure that the property names and their backup fields have different
name. In my example the fileds start with small letters and the properties
with capitals.
 

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