Jump to content
  • Advertisement
Sign in to follow this  
dxFoo

[.net] C#: structs within classes?

This topic is 4845 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm wondering if it's possible to add structs within classes for the sake of better management. Here's some code for an example. C++ had structs within structs. In C#, does it need to be embedded classes?
    class Common
    {
        private String name;

        public struct AvailableFood
        {
            public int Wine, Bread, Ale, Fish, Cheese, Grain, Flour, Water, Milk;
        }
    }


Share this post


Link to post
Share on other sites
Advertisement
Just remember to declare the class itself public, or you might have some accessibility issues using that struct outside that reference type.

Share this post


Link to post
Share on other sites
Thanks for the tips. I'm having an access specifier missing or something similar. Any help is appreciated.


class Common
{
public class Food
{
public int Wine, Bread, Ale, Fish, Cheese, Grain, Flour, Water, Milk;
}
}




Common PC = new Common();
PC.Food.Wine = 5; // can't find Food!

Share this post


Link to post
Share on other sites
You're misunderstanding what that particular code accomplishes. It merely defines the type Food inside Common, but does not instantiate Food. Therefore:


// your definition of Common here...

// valid code:
Common c = new Common();
Common.Food f = new Common.Food();
f.Wine = 3;

// invalid:
c.Food.Wine = 3; // can't do this since Food is a type, not a variable






I assume you want something like this:


class Common
{
public class Food
{
public int Wine;
}

private Food _food = new Food();

public Food Food
{
get { return _food; }
}
}

Common c = new Common();
c.Food.Wine = 3; // accesses the Food property of Common, which is of type Common.Food


I also noticed you used struct in your original post, then switched it to class in your later post. They are quite different things. Here's a quick summary of the differences. More detailed description here, in the section titled "Reference and Value Types".

[Edited by - mutex on August 8, 2005 10:21:45 PM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!