Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - Nested classes? Properties with properties?

Tags:

c#

class

nested

I would like to create a class with properties that have subproperties...

In other words, if I did something like:

Fruit apple = new Fruit();

I would want something like:

apple.eat(); //eats apple
MessageBox.Show(apple.color); //message box showing "red"
MessageBox.Show(apple.physicalProperties.height.ToString()); // message box saying 3

I would think it would be done like:

class Fruit{
    public void eat(){
        MessageBox.Show("Fruit eaten");
    }
    public string color = "red";
    public class physicalProperties{
        public int height = 3;
    }

}

...but, if that were working, I wouldn't be on here...

like image 404
mowwwalker Avatar asked Sep 18 '25 12:09

mowwwalker


2 Answers

So close! Here's how your code should read:

class Fruit{
    public void eat(){
        MessageBox.Show("Fruit eaten");
    }
    public string color = "red";
    public class PhysicalProperties{
        public int height = 3;
    }
    // Add a field to hold the physicalProperties:
    public PhysicalProperties physicalProperties = new PhysicalProperties();
}

A class just defines the signature, but nested classes don't automatically become properties.

As a side note, there's also a couple things I'd recommend, to follow .NET's "best practices":

  • Don't nest classes unless necessary
  • All Public members should be Properties instead of Fields
  • All Public members should be PascalCase, not camelCase.

I'm sure there's plenty of documentation on best practices too, if you're so inclined.

like image 154
Scott Rippey Avatar answered Sep 21 '25 02:09

Scott Rippey


class Fruit{
    public void eat(){
        MessageBox.Show("Fruit eaten");
    }
    public string color = "red";
    //you have declared the class but you havent used this class
    public class physicalProperties{
        public int height = 3;

    }
    //create a property here of type PhysicalProperties
    public physicalProperties physical;
}
like image 20
Haris Hasan Avatar answered Sep 21 '25 02:09

Haris Hasan