Accessing property read value inside C# object initializer - c#

I would like to reference a property on an object within an object initializer. The problem is that the variable does not yet exist, so I cannot reference it like normal (object.method). I do not know if there is a keyword to reference the object in creation during the object initialization.
When I compile the following code I get the error - 'The name 'Width' does not exist in the context. I understand why I get this error, but my question is: Is there any syntax to do this?
public class Square
{
public float Width { get; set; }
public float Height { get; set; }
public float Area { get { return Width * Height; } }
public Vector2 Pos { get; set; }
public Square() { }
public Square(int width, int height) { Width = width; Height = height; }
}
Square mySquare = new Square(5,4)
{
Pos = new Vector2(Width, Height) * Area
};
I would like to reference the properties "Width", "Height", and "Area" in terms of "mySquare".

You can't do this as written, but you can define the Pos property to do the same thing. Instead of
public Vector2 Pos { get; set; }
do this
public Vector2 Pos
{
get
{
return new Vector2(Width, Height) * Area;
}
}
Of course, then any square has the same definition for Pos. Not sure if that's what you want.
Edit
Based on your comment I take it you want to be able to specify the value of Pos deferently for different Squares. Here's another idea. You could add a third argument to the constructor which takes a delegate, and then the constructor could use the delegate internally to set the property. Then when you create a new square you just pass in a lambda for the expression you want. Something like this:
public Square(int width, int height, Func<Square, Vector2> pos)
{
Width = width;
Height = height;
Pos = pos(this);
}
then
Square mySquare = new Square(4, 5, sq => new Vector2(sq.Width, sq.Height) * sq.Area);

Related

There is no argument that corresponds to the required formal paramter

I have only just started learning C# so excuse this basic question. I am experimenting with C# inheritance and want to inherit the properties from Shape class into the Rectangle class. The Rectangle class below gives me an error:
"There is no argument that corresponds to the required formal
parameter 'height' of 'Shape.Shape(double.double)'
Is anyone able to tell me why this is happening?
class Shape
{
public double Height { get; set; }
public double Width { get; set; }
public Shape (double height, double width)
{
Height = height;
Width = width;
}
public double calculateArea()
{
double Area = (Height * Width);
return Area;
}
}
class Rectangle : Shape
{
public Rectangle(double height, double width)
{
Height = height;
Width = width;
}
static void Main(string[] args)
{
Rectangle rectangle = new Rectangle(15, 19);
double areaOfRectangle = rectangle.calculateArea();
Console.WriteLine(areaOfRectangle);
}
}
In c#, the base keyword is used to access base class members such as properties, methods, etc. in the derived class. so you have to act like below:
public Rectangle(double height, double width) : base(height, width) { ... }
for learning more about base you can follow this. good luck.

Setting the argument/parameter in C#

I've been working on an assignment for class, beginners C#. I've hit a point where I do not know what to do next. This is the question and it involves argument/parameters...
Define the output of the "area" property calculation such that a user can initialize an instance of the "Circle" class by setting the argument/parameternamed"radius" (in the Constructor) and subsequently call a method named "ShowArea" to display the area of the new circle instance using the formula: (where r = radius, A = area, π= pi)
This is what I have so far:
namespace IndividualAssignment2
{
public class Shape
{
public virtual int area { get; set; }
}
public class Circle : Shape
{
double radius;
public override int area { get; set; }
double ShowArea = 3.14 * Math.Pow(radius,2);
}
public sealed class Square : Shape
{
int height;
}
}
How would I implement this into my code? My double ShowArea is incorrect because radius is underlined. I think understanding this question would help with that issue. Thank you.
If I'm understanding you correctly, ShowArea is a method and not a field. Which means your Circle class should be something like:
public class Circle : Shape
{
double _radius;
// Constructor for the Circle that has radius as a parameter
public Circle(double radius)
{
_radius = radius;
}
// Method that returns the area of the circle using radius value from constructor
public double ShowArea()
{
return Math.Pi * Math.Pow(_radius, 2.0);
}
}
Your class design must be reviewed.
public abstract class Shape
{
public abstract double Area { get; }
}
public class Circle : Shape
{
public Circle(double radius)
{
Radius = radius;
}
private double Radius { get; set; }
public override double Area => 3.14 * Math.Pow(Radius, 2);
}
public class Square : Shape
{
public Square(double edge)
{
Edge = edge;
}
private double Edge { get; set; }
public override double Area => Math.Pow(Edge, 2);
}
Your declaration of the method ShowArea is not correct. You are declaring a field instead.
You should read up more on methods. You were also tasked to declare a constructor with a parameter to set the radius, which I don't find it in your code.

struct in C# doesn't work as expected

I'm working on a simple application and I'm a little confused. I have a simple struct Point with int x and int y. And I use it for Line
public class Line : Shape {
public Line() {
PointA = new Point(x: 0, y: 0);
PointB = new Point(x: 0, y: 0);
}
public Point PointA { get; set; }
public Point PointB { get; set; }
}
and somewhere
var line = new Line();
line.PointB = new Point(x: 4, y: 2);
Console.WriteLine($"Line start at {line.PointA.GetX()}:{line.PointA.GetY()}; end at {line.PointB.GetX()}:{line.PointB.GetY()}");
for (int i = 0; i < 10; i++) {
line.PointB.IncrementX();
line.PointB.IncrementY();
}
Console.WriteLine($"Line start at {line.PointA.GetX()}:{line.PointA.GetY()}; end at {line.PointB.GetX()}:{line.PointB.GetY()}");
Here need to increment x and y of Point but result doesn't change:
Line start at 0:0; end at 4:2
Line start at 0:0; end at 4:2
What I'm doing wrong? It seems strange. Are there some specific rules to use struct in C#. I know that this is a value type but I think it is a good for Point. All examples uses struct for Point. Please help?
Point:
public struct Point {
private int _x;
private int _y;
public Point(int x, int y)
: this() {
_x = x;
_y = y;
}
public void IncrementX() {
_x++;
}
public void IncrementY() {
_y++;
}
public int GetX() {
return _x;
}
public int GetY() {
return _y;
}
}
Struct is a value type. And it is passed by value (i.e. by creating copy of all fields) instead of passing reference to struct instance. So when you do
line.PointB.IncrementX()
When you call getter of PropertyB, it returns copy of Point which is stored at PropertyB backing field. And then you call increment on copy. Thus original value will stay unchanged.
Further reading: Value and Reference Types and especially Mutating Readonly Structs which says
mutable value types are evil. Try to always make value types
immutable.
What you can do if you want to actually move line point?
Change Point type to class. Then it will be passed by reference, and all methods will be called on original point which you store in Line.
Assign new (modified) point instance to line
I.e. you should store copy, change it and assign back
var point = line.PointB; // get copy
point.IncrementX(); // mutate copy
point.IncrementY();
line.PointB = point; // assign copy of copy
You can also make your Point struct immutable (the best thing you can do for value types):
public struct Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
public Point IncrementX() => new Point(X + 1, Y);
public Point IncrementY() => new Point(X, Y + 1);
public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);
}
And now changing location will look like
line.PointB = line.PointB.Move(1, 1);

c# how do I do a private set property?

I am creating a VECTOR object like so, but I am initializing it in the constructor:
public VECTOR position { get; private set; }
I am doing this operation:
position.x += 2;
VECTOR has a variable x defined as:
public double x { get; set; }
I get the error when I do the +=2 operation that says:
Cannot modify the return value of 'Projectile.position' because it is
not a variable
I want to be able to modify the position vector in the current class, and I want it to be accessible but not modifiable in other classes.
Probably, your problem is with the Vector class actually being a struct. Assume you have the following declarations:
public class Projectile
{
public VECTOR position { get; private set; }
public Projectile()
{
position = new VECTOR();
}
}
public struct VECTOR
{
public double x {get; set;}
}
You cant edit properties of the position property directly because you are accessing a copy of that field (explained here).
If you don`t want to convert your VECTOR into a class you can add a method that updates the position of your projectile:
public void UpdatePosition(double newX)
{
var newPosition = position;
newPosition.x = newX;
position = newPosition;
}
That will create a copy of the position, then update its x property and override the stored position. And the usage would be similar to this:
p.UpdatePosition(p.position.x + 2);
Expose the X property (and others) of VECTOR in a class.
public class myObject {
private VECTOR position;
public double X { get{return position.x;}set{position.x=value;}}
}
Usage example:
myObject.X += 2;

C# XNA pass by reference classes in constructor

I'm making a vector graphics game in XNA. I've designed a Line class to rotate around a central point to help draw specific shapes. In order to maintain a single point of truth, is there a way to pass a reference to the center of the shape to all of the lines I create, so that updating the center's position will also update the lines' positions? I thought something like this would work:
class Line
{
private Vector2 start;
private double length;
private double angle;
public Line(ref Vector2 start, double length, double angle){
this.start = start;
this.length = length;
this.angle = angle;
}
}
class Obj
{
private Vector2 center;
private Line[] lines;
public Obj(){
center = new Vector2(50,50);
lines = new Lines[5];
for (int i = 0; i < 5; i++){
lines[i] = new Line(ref center,30, (i/5 * 2 * Math.PI));
}
}
}
but the lines do not update when I move the center. What am I doing wrong?
Although the struct is correctly passed by reference to Line, when you assign it internally:
public Line(ref Vector2 start, double length, double angle){
this.start = start;
}
You are actually taking a copy of the struct.
If you ever find yourself needing reference type semantics of struct beyond passing it to a single method then you likely need to reconsider using class.
You can either re-implement the type in a class or wrap the Vector2 in a class and use that:
class Vector2Class
{
public Vector2 Centre;
public Vector2Class(Vector2 inner)
{
Centre = inner;
}
}
class Line
{
private Vector2Class _centre;
public Line(Vector2Class centre)
{
_centre = centre;
}
}
Be aware that you are still working against a copy, but if you share the class you'll all be working on the same copy.
Personally, I would avoid the wrapper and make my own class for representing "centre". This is supported by the largely accepted idea that struct types should be immutable, but you seem to need to mutate the values to keep the representation true.
class CentreVector<T>
{
public <T> X { get; set; }
public <T> Y { get; set; }
}
This only lets you share the data, it doesn't actually notify the lines that the centre has changed. For that you would need some sort of event.
Edited with alternative solution
The problem you're having is because Vector2 is a value type, you're correctly passing it by ref in your methods parameter but then making a local copy of it with the assignment.
I'm not totally sure if you could maintain a pointer to Vector2 in the way that you're thinking but you could create your own Vector2 class that would be a reference type.
class ObjectVector2
{
public float X { get;set; }
public float Y { get; set; }
}
I would like to suggest a slightly different way to achieve the same result by holding a reference to the obj that the lines are a part of.
class Line
{
private Vector2 Center { get { return parent.center; } }
private double length;
private double angle;
Obj parent;
public Line(Obj parent, double length, double angle)
{
this.parent = parent;
this.length = length;
this.angle = angle;
}
}
class Obj
{
public Vector2 center;
private Line[] lines;
public Obj()
{
center = new Vector2(50, 50);
lines = new Lines[5];
for (int i = 0; i < 5; i++)
{
// passing the reference to this Obj in the line constructor.
lines[i] = new Line(this, 30, (i / 5 * 2 * Math.PI));
}
}
}

Categories