473,385 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 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 1507
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.