primary constructor naming convention

Hi! I was wondering if there is a naming convention for primary constructor parameters on a class. Let's say I have class Point(int x, int y) and now I want to add a method to this class with an int x parameter. AFAICT I then can't really resolve the name conflict between the two in the method body, so I was wondering if I should rename the primary constructor parameters to e.g. _x and _y or if I should instead rename the method parameter to avoid the conflict. Thanks!
6 Replies
maxmahem
maxmahem8mo ago
hmm? I'm a bit confused. There should not be any conflict between a primary ctor (or any ctor) and any member function. Something like a Point is a great candidate for a record struct though.
knut.wannheden
knut.wannhedenOP8mo ago
class Point(int x, int y)
{
Point Offset(int x, int y)
{
// ???
}
}
class Point(int x, int y)
{
Point Offset(int x, int y)
{
// ???
}
}
It is a silly example which would be better done with records, as you say. I was just trying to use something simple to convey the question.
maxmahem
maxmahem8mo ago
okay I see what you are talking about better now. I would only rely on the "auto fields" when there is no obvious conflict. If there is, I would just do like:
class Point(int x, int y) {
public int X { get; } = x;
public int Y { get; } = y;
public Point Offset(int x, int y) => new Point(X + x, Y + y);
}
class Point(int x, int y) {
public int X { get; } = x;
public int Y { get; } = y;
public Point Offset(int x, int y) => new Point(X + x, Y + y);
}
especially in a case like Point where you are likely to want to expose the X and Y.
knut.wannheden
knut.wannhedenOP8mo ago
I see. Thanks! I was just wondering if there was some established convention to resolve these kinds of conflicts.
maxmahem
maxmahem8mo ago
I would say that "upgrading" them to properties (private or public) is probably the way to resolve these.
Unknown User
Unknown User8mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server