Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,688 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
hi, i'm new to c#, i want solve this problem :
public class Location
{
public int X { get; set; }
public int Y { get; set; }
public Location() : this(0, 0) { }
public Location(int x, int y)
{
X = x;
Y = y;
}
}
public class Car
{
public Location CurrentLocation { get;
private set; }
void SomeCarMethod()
{
CurrentLocation.X = 5; // it's ok
CurrentLocation = new Location(1, 2); // not preferred
}
}
public class TempClass
{
public Car MyCar { get; set; }
void TempMethod()
{
MyCar.CurrentLocation.X = 6; // it works **but** I don't want X to be accessible here
var t = MyCar.CurrentLocation.X; // it's ok
}
}
i'm using c# wpfCore3.1 vs2019
You can use interface ILocation and a private Location class
public interface ILocation
{
int X { get; }
int Y { get; }
}
public class Car
{
private Location _currentLocation;
public ILocation CurrentLocation => _currentLocation;
public void SomeCarMethod()
{
_currentLocation.X = 5; // it's ok
_currentLocation = new Location(1, 2); // not preferred
}
private class Location : ILocation
{
public int X { get; set; }
public int Y { get; set; }
public Location() : this(0, 0) { }
public Location(int x, int y)
{
X = x;
Y = y;
}
}
}
public class TempClass
{
public Car MyCar { get; set; }
public void TempMethod()
{
MyCar.CurrentLocation.X = 6; // X is not accessible here
var t = MyCar.CurrentLocation.X; // it's ok
}
}
or a Location class and a private RwLocation class
public class Location
{
public int X { get; }
public int Y { get; }
}
public class Car
{
private RwLocation _currentLocation;
public Location CurrentLocation => _currentLocation;
public void SomeCarMethod()
{
_currentLocation.X = 5; // it's ok
_currentLocation = new RwLocation(1, 2); // not preferred
}
private class RwLocation : Location
{
public int X { get; set; }
public int Y { get; set; }
public RwLocation() : this(0, 0) { }
public RwLocation(int x, int y)
{
X = x;
Y = y;
}
}
}
public class TempClass
{
public Car MyCar { get; set; }
public void TempMethod()
{
MyCar.CurrentLocation.X = 6; // X is not accessible here
var t = MyCar.CurrentLocation.X; // it's ok
}
}