0

I have 5 Properties within my class that are all very similar; I want to group them. The class they are contained in used to look like this:

class Car
{
   public string PropA { get; set; }
   public string PropB { get; set; }
   public string PropC { get; set; }

   public Car() { }
}

So with Intellisense, I would be presented with:

Car car = new Car();
car.PropA
   .PropB
   .PropC

..I would be presented with the 3 properties. What I want is for it to be contained within it's own little group, so I would have to do:

car.Props.PropA = "example";

I created a partial class to hide them in, but I am not sure if this is the correct way to do it:

class Car
{
   public Props { get; set; }

   public Car() { }
}

partial class Props
{
   public string PropA { get; set; }
   public string PropB { get; set; }
   public string PropC { get; set; }
}

Is there a better way to go about this? I ask because I am creating a class library and usability is very important.

har07
  • 88,338
  • 12
  • 84
  • 137
user3761858
  • 231
  • 2
  • 6
  • 13

2 Answers2

3

The partial keyword is used to split a class's implementation among multiple files. Knowing that, it doesn't help (or hurt) in this situation.

Without knowing more about your design, your solution seems reasonable. Just get rid of the partial keyword, it's not appropriate here.

Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88
1

Agreed with what Patrick said. I had a question about your public setters though, and this is something I've been curious about how to handle myself.

if you're hoping for other people to use thing class (and assuming this wasn't just a mocked up example) are you sure you want people to just be able to willy nilly be able to set properties in your classes without going through a method/function that validates and/or handles the setting of the property?

this can be done like:

public class Props
{
   public string PropA { get; private set; }
   public string PropB { get; private set; }
   public string PropC { get; private set; }
}

public Props() { }

public SetProps(string propA, string propB, string propC)
{
    this.PropA = propA;
    this.PropB = propB;
    this.PropC = propC;
}

Now obviously doing something like this would depend on the nature of the requirements around the props (and this is an extremely simple example - all props have to be set at the same time). But with public setters a user of the class would not necessarily know the nature of the requirements, and the public setters could potentially allow them a way around how it was intended the class be used.

Kritner
  • 13,557
  • 10
  • 46
  • 72