472,811 Members | 1,281 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,811 software developers and data experts.

Struct Help

I'm new to C# (literally 2 days) and need a bit of help understanding
an error.

struct Blah
{
int x;
int y;

public int X
{
get
{
return x;
}
set
{
this.x = value;
}
}

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

class MainApp
{
public static void Main()
{
Blah test;

test.Y = 1;

}
}

With the above code I get the following error:

"Use of unassigned local variable 'test'"

But I remove the data member properties in 'struct Blah' I can happily
assign to test.y.

If I use properties (get, set)do I need to initialise the struct
members first?

Dec 4 '05 #1
9 1488
variables in C# when declared must be initialized.

Blah test;

should be Blah test= new Blah();

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"^MisterJingo^" wrote:
I'm new to C# (literally 2 days) and need a bit of help understanding
an error.

struct Blah
{
int x;
int y;

public int X
{
get
{
return x;
}
set
{
this.x = value;
}
}

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

class MainApp
{
public static void Main()
{
Blah test;

test.Y = 1;

}
}

With the above code I get the following error:

"Use of unassigned local variable 'test'"

But I remove the data member properties in 'struct Blah' I can happily
assign to test.y.

If I use properties (get, set)do I need to initialise the struct
members first?

Dec 4 '05 #2
Quote from microsoft:

When you create a struct object using the new operator, it gets created and
the appropriate constructor is called. Unlike classes, structs can be
instantiated without using the new operator. If you do not use new, the
fields will remain unassigned and the object cannot be used until all of the
fields are initialized.
"Peter Bromberg [C# MVP]" <pb*******@yahoo.nospammin.com> wrote in message
news:E3**********************************@microsof t.com...
variables in C# when declared must be initialized.

Blah test;

should be Blah test= new Blah();

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"^MisterJingo^" wrote:
I'm new to C# (literally 2 days) and need a bit of help understanding
an error.

struct Blah
{
int x;
int y;

public int X
{
get
{
return x;
}
set
{
this.x = value;
}
}

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

class MainApp
{
public static void Main()
{
Blah test;

test.Y = 1;

}
}

With the above code I get the following error:

"Use of unassigned local variable 'test'"

But I remove the data member properties in 'struct Blah' I can happily
assign to test.y.

If I use properties (get, set)do I need to initialise the struct
members first?

Dec 4 '05 #3
"J. Verdrengh" <un***@tiscali.be> a écrit dans le message de news:
43***********************@news.skynet.be...

| When you create a struct object using the new operator, it gets created
and
| the appropriate constructor is called. Unlike classes, structs can be
| instantiated without using the new operator. If you do not use new, the
| fields will remain unassigned and the object cannot be used until all of
the
| fields are initialized.

Which translated from MSspeak means do this :

struct Blah
{
int x = 0;
int y = 0;

...
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Dec 4 '05 #4
The book I was reading said structs can be declared without the "new"
operator or empty constructor call - which is where the confusion arose
from. Should this be avoided?

Thanks,

Chris

Dec 4 '05 #5
When I try that I get the message:

"'Blah.x': cannot have instance field initializers in structs"

Dec 4 '05 #6
MJ....

As a first approximation, you can look at a structure as a "lightweight
class
with value semantics". However, unlike a class, you cannot extend a
structure,
define a destructor or initialize fields at declaration in a structure.
You cannot
define a no-arg constructor in a structure since the compiler will
insist on
doing this for you. If you do define a constructor, it is your
responsibility to
initialize all fields in the structure.

As an example, the idiom of returning a bool value and setting a
lastError
message in an instance field is not very object oriented and is not
thread
safe. Here is a prototype immutable structure aptly named BoolStruct
that is
object based and potentially thread safe.

// wraps bool result, message and source as value type
// two helper properties for bool result: B and Value
// immutable structure
public struct BoolStruct
{
public readonly bool isSuccess;
public readonly String message;
public readonly String source;
public BoolStruct(bool isSuccess,String message, String source)
{
if (message == null) {message= "";}
if (source == null) {source= "";}
this.isSuccess= isSuccess;
this.message= message;
this.source= source;
}
public bool B // helper
{
get {return isSuccess;}
}
public bool Value
{
get {return isSuccess;}
}
}

http://www.geocities.com/Jeff_Louie/OOP/oop11.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Dec 4 '05 #7
The reason is that a 'struct' is just a value type. What you're trying
to do is the same as

int y;
int x;

x = y;

you need to assign something to 'y' before you can use it. (or in the
case of a struct you can also use new)

Dec 4 '05 #8
The book I was reading said structs can be declared without the "new"
operator or empty constructor call - which is where the confusion arose
from.


You can in some cases, but then you have to manually initialize each
struct field. And to do that, they have to be accessible to you. In
this case both x and y are private so you can't access them directly,
therefore you have to use the new operator and let a constructor
handle the initializeation (all the default ctor does really is
initialize the struct's fields to their default values).
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Dec 4 '05 #9
Indeed, what Joanna proposes is not allowed. Either you create a structure
with the new operator, or you declare the structure as you did, but in the
latter case you first have to manually assign a value to each instance
field.

So i guess this won't give an error (not tested):
public static void Main()
{
Blah test; test.x = 1;
test.y = 1;
test.Y = 1;

}
When I try that I get the message:

"'Blah.x': cannot have instance field initializers in structs"

Dec 4 '05 #10

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

Similar topics

2
by: Angelo Secchi | last post by:
I'm trying to use the unpack method in the struct module to parse a binary file without success. I have a binary file with records that include many fields for a total length of 1970. Few days ago...
5
by: Roy Hills | last post by:
When I'm reading from or writing to a network socket, I want to use a struct to represent the structured data, but must use an unsigned char buffer for the call to sendto() or recvfrom(). I have...
4
by: Angus Comber | last post by:
Hello I have received a lot of help on my little project here. Many thanks. I have a struct with a string and a long member. I have worked out how to qsort the struct on both members. I can...
20
by: fix | last post by:
Hi all, I feel unclear about what my code is doing, although it works but I am not sure if there is any possible bug, please help me to verify it. This is a trie node (just similar to tree nodes)...
4
by: PCHOME | last post by:
Hi! I have questions about qsort( ). Is anyone be willing to help? I use the following struct: struct Struct_A{ double value; ... } *AA, **pAA;
2
by: Arne Styve | last post by:
Hi, I have an API written in C that came with some graphics cards we are going to use in a project. I need to write a small application where this API is to be used, and I decided to try out...
28
by: Tamir Khason | last post by:
Follwing the struct: public struct TpSomeMsgRep { public uint SomeId;
4
by: JR | last post by:
I need some help. I am trying to return a dirent struct location so i can access what the function found in main(). I dont understand pointers very well and think that is were i am getting it...
9
by: sean.scanlon | last post by:
can someone help understand how i can could access a struct field dymanically like: foo->fields ? when i try to compile this i get the following error: 'struct pwd' has no member named 'fields'...
4
by: jadeivel756 | last post by:
I BADLY NEED YOUR HELP...... HELP... hOW TO Pass value to a struct type and permanently store the data after youve given the data.The programming language is C. My problem is that as I exit the...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth

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.