Reputation: 3459
I created a struct, that has another struct as a property. I want to be able to do something like this:
MyColor.RGBColor.R = 255;
MyColor and RGBColor being the structs I created. This doesn't work, I set a whole new value to RGBColor, but that's not straightforward and there has to be an easier way. Currently, I have to do this:
MyColor.RGBColor = new RGBColor(255, MyColor.RGColor.G ...)
I'm pretty sure if I stopped encapsualting the private properties in public properties, and just make them public in the first place, I won't have this problem... but I always read that this is a bad thing to do, so how can I go about this? Thanks
EDIT:
This is how I implement the properties currently:
private rgbcolor _RGBColor;
public rgbcolor RGBColor {
get {
return _RGBColor;
}
set {
_RGBColor = value;
}
}
Upvotes: 1
Views: 460
Reputation: 1136
When you use value types (structs) you should keep in mind that passing them in methods as parameters or returning from methods (also in some other cases) always cause making a copy of that object. Properties are just the methods after compilation. So your code in fact equal:
var copy = MyColor.RGBColor; // you get a copy now
copy.R = 255; // and now you change a copy, not the original object's value
C# compiller understand that this is an error and don't compile your desired variant. Because of this it's strongly recomended to create imutable structs. In your case it's better to use classes.
Upvotes: 0
Reputation: 27974
This is expected behavior. By accessing the property RGBColor
, you invoke its getter method, which returns the struct's instance by value. Even though you would then assign (which, in fact, even doesn't compile) a value into R
, the struct itself is not stored back into the RGBColor
property — even if it had a setter. This is just how value types behave.
If you can, just avoid using structs. In the world of classes with automatic references and properties with getter/setter methods they tend to be very counter-intuitive. Trying to represent small classes (in terms of data size) as structs is premature optimization.
Note: What you call a “private property” is not a property. It's a member field.
Upvotes: 2
Reputation: 4112
You should look at conventions for class names vs. variable names. You seem to have it somewhat backwards in your implementation.
Here's what I think you're trying to do:
private rgbcolor _RGBColor = new rgbcolor();
public rgbcolor RGBColor {
get {
return _RGBColor;
}
}
Once that's in place, you should be able to do something like (assuming there's a property R on rgbcolor)
MyColor.RGBColor.R = 255;
This will work because the instance for MyColor.RGBColor will exist when the RGBColor property is accessed.
Upvotes: 0