benjm-ma
Member
- Joined
- Jun 2, 2020
- Messages
- 14
- Programming Experience
- 1-3
Hey Guys,
Here is the code I am trying to compile:
When attempting to compile using mcs (Mono C# compiler version 6.8.0.123) I get the following errors:
I've omitted some of the above errors as it repeats.
To eliminate the last compilation error there I extended the body of the if statements within NormalizePoint to assign p to itself as the struct's values should not change.
This gets a warning from the compiler so I know I'm going about this the wrong way. What would be the better way to achieve what I'm trying to do here in regards to
using an out variable within a function which may not modify the variable under certain conditions?
For the first two methods, I understand what the compiler is telling me, I just don't see how it applies to the code (maybe I don't understand). I don't really know what to do
to resolve this error as I am under the impression that the struct and it's fields are initialized within Main before it is passed to NormalizePoint.
Any help and suggestions would be greatly appreciated.
Thank you
Here is the code I am trying to compile:
C#:
using System;
class Exercise {
static void Main()
{
Point p;
p.x = 40.0;
p.y = 45.0;
if (NormalizePoint(out p)) {
Console.WriteLine ($"x normalized to {p.x}\ny normalized to {p.y}");
} else {
Console.WriteLine ($"Points cannot be normalized");
}
}
public struct Point
{
public double x;
public double y;
public Point (double _x, double _y)
{
x = _x;
y = _y;
}
}
public static bool NormalizePoint (out Point p)
{
if (p.x < 1d || p.y < 1d) return false;
if (p.x > 100d || p.y > 100d) return false;
p = new Point (p.x / 100d, p.y / 100d);
return true;
}
}
When attempting to compile using mcs (Mono C# compiler version 6.8.0.123) I get the following errors:
struct.cs(32,10): error CS0170: Use of possibly unassigned field `x'
struct.cs(32,22): error CS0170: Use of possibly unassigned field `y'
struct.cs(30,48): error CS0177: The out parameter `p' must be assigned to before control leaves the current method
I've omitted some of the above errors as it repeats.
To eliminate the last compilation error there I extended the body of the if statements within NormalizePoint to assign p to itself as the struct's values should not change.
This gets a warning from the compiler so I know I'm going about this the wrong way. What would be the better way to achieve what I'm trying to do here in regards to
using an out variable within a function which may not modify the variable under certain conditions?
For the first two methods, I understand what the compiler is telling me, I just don't see how it applies to the code (maybe I don't understand). I don't really know what to do
to resolve this error as I am under the impression that the struct and it's fields are initialized within Main before it is passed to NormalizePoint.
Any help and suggestions would be greatly appreciated.
Thank you