I have a class :
public class Foo {
// here so serializer can materialize the class
public Foo(){
}
public Foo(string bar){
ImportantStuff = bar;
}
public string ImportantStuff { get; set;}
public string OtherBits{ get; set;}
public int eresting { get; set;}
}
How can i protect ImportantStuff being set by anyone except the serializer (json.net/ EF) ?
You can place access modifiers on property accessors.
[JsonProperty]
public string ImportantStuff { get; private set; }
// ^^^
If you really must prevent Foo members from changing it, use a private setter AND move the property to a base class. But I interpreted the question to mean that you don't want consumers of the class to be able to set it.
The JsonProperty attribute is required because JSON.net will default to skipping properties with non-public setter. See Private setters in Json.Net and http://daniel.wertheim.se/2010/11/06/json-net-private-setters/
(Naturally other code that runs with full permission can do anything it wants to the insides of your object, if the right hoops are jumped through)
Related
I'm writing a little game, and the game has a State class to keep track of game state. The State class is only intended to be modifiable by Commands (command pattern). The State class includes lists of other classes - e.g. a Faction class, which contains members like resources, a list of owned Units, etc.
How can I make the deep innards of State readable from other classes, without also leaking writable references inside of State itself?
Currently, I have specialized getters like State.GetOwnerOfUnitAtLocation(x), which only return safe values (int factionid etc.), but I am beginning to need a lot of these, and the class is getting really unwieldy. I would prefer to have those methods in more appropriate locations (Map.Units.GetOwner(x) or something), but I don't know how to expose the internals of State to other classes in a safe way.
Relatedly, Command is an interface that currently lives inside of the State class, along with all the actual commands that implement it, so that it can modify private members of State. Is there a better way to implement this?
Edit: A selection of code from State to illustrate the first issue:
public partial class State
{
public int Turn {get; private set;} = 1;
private Dictionary<Vector2, FactionsMgr.Faction> _unit_map = new Dictionary<Vector2, FactionsMgr.Faction>();
public int GetUnitRemainingMobility(Vector2 pos)
{
if (IsUnitAt(pos))
{
FactionsMgr.Faction owner = _unit_map[pos];
int taken_movement = owner.units[pos]._taken_movement;
int max_mobility = UnitsMgr.GetMaxMobility(owner.units[pos].type);
return max_mobility - taken_movement;
}
else
{
GD.Print("Warning: GetUnitRemainingMobility asked for unknown unit: ", pos);
return -1;
}
}
}
Since FactionsMgr.Faction is mutable, let's suppose that it has writable properties like this:
class Faction {
public int Foo { get; set; }
public string Bar { get; set; }
public float Baz { get; set; }
public SomeOtherMutableThing AnotherThing { get; set; }
}
You should create a corresponding read only interface for it, and make Faction implement it:
interface IReadOnlyFaction {
// exclude all members that can change Faction's state
int Foo { get; }
string Bar { get; }
float Baz { get; }
IReadOnlySomeOtherMutableThing AnotherThing { get; }
}
interface IReadOnlySomeOtherMutableThing {
// do the same thing there...
}
class Faction: IReadOnlyFaction {
public int Foo { get; set; }
public string Bar { get; set; }
public float Baz { get; set; }
public SomeOtherMutableThing AnotherThing { get; set; }
// you need an explicit interface implementation here, unless you are using C# 9
IReadOnlySomeOtherMutableThing IReadOnlyFaction.AnotherThing => AnotherThing;
}
Then, you can declare public members in State as of type IReadOnlyFaction, and delegate them to a private member of type Faction. The private member is also what the Command class will modify.
private Faction someFaction;
public IReadOnlyFaction SomeFaction => someFaction;
That is the general case. However, if you have collections of these mutable types, like your dictionary of _unit_map, you would need to do a bit more work.
You would still have a public read only member and a private mutable member, but the delegating process is less straightforward. You would need a wrapper.
private Dictionary<Vector2, FactionsMgr.Faction> _unit_map = new();
public IReadOnlyDictionary<Vector2, IReadOnlyFaction> UnitMap;
// ...
// in the constructor of State...
// using the ReadOnlyDictionaryWrapper class from the linked answer
UnitMap = new ReadOnlyDictionaryWrapper<Vector2, FactionsMgr.Faction, IReadOnlyFaction>(_unit_map);
I am making a save/load system for a big game project in C#.
Each class that has to be saved implements a method DoSnapshot().
Inside the method, the programmer must make a call to a function for every field in the class - either DoSnapshot(foo) if foo should be saved, or Ignore(foo) if it should not.
I have a DoSnapshot method for many primitive types like DoFloat, DoString as well as versions for complex types.
I have 100s of classes and the project is still being developed.
Is it possible to add some kind of verification that all of the fields in each class are either used in a Snapshot() or an Ignore() call? Omitting fields would cause bugs.
The verification could either be runtime, or compile-time. I only want to use it during development, it will not be released to users.
You could add an attribute to the fields that need to be saved, and then loop over every property in your class in the DoSnapshot method. When the property has the attribute you're looking for, you call Snapshot, otherwise you call Ignore.
public class SomeClass : SomeBaseClass
{
[Required]
public string Foo { get; set; }
public string Bar { get; set; }
public override void DoSnapshot()
{
var properties = this.GetType().GetProperties();
foreach (var property in properties)
{
var isRequired = property.GetCustomAttributes(typeof (RequiredAttribute), false).Length > 0;
if (isRequired)
{
// Something
}
else
{
// SomethingElse
}
}
}
}
What i would do is create an attribute and "tag" each field if it should be saved or not. Then, at runtime, i would query the class using reflection to get all fields which should be serialized:
public class RandomClass
{
public string Foo { get; set; }
[Ignore]
public int Bar { get; set; }
}
public class IgnoreAttribute : Attribute
{
}
class Program
{
static void Main(string[] args)
{
var properties = typeof(RandomClass).GetProperties()
.Where(prop => !prop.IsDefined(typeof(IgnoreAttribute), false));
// Serialize all values
}
}
I have a situation where I have some DTO classes that should be implemented like:
public class City
{
public string Name { get; set; }
public State State { get; set; }
}
public class State
{
public string Name { get; set; }
}
The problem is, these are actually DTO classes for REST XML resources. And the City resource may include the State resource inline, or it may simply provide the resource ID (a URI). I am handling access to the DTO via the Repository pattern and would like it to be transparent to clients whether State is lazy loaded or not (like how NHibernate does with it's entity classes).
So my current plan is to use Castle DynamicProxy to create a proxy object when the REST Repository detects that the class isn't fully "hydrated" (i.e. not everything is inline). The proxy object will know how to lazy load attributes as needed.
To actually implement this, however, the only thing I've come up with is to have backing attributes for all relationships and put the Xml attributes on those. So the strategy looks like this:
[XmlType]
public class City
{
[XmlElement]
public string Name { get; set; }
[ToOneRestRelationship(BackingPropertyName = "StateBacking")]
public State State { get; set; }
[XmlElement(Name = "state")]
public ResourceBase StateBacking { get; set; }
}
[XmlType]
public class State
{
[XmlElement]
public string Name { get; set; }
}
Then the Repository object knows to set up the proxy object to either get the object from the StateBacking property and use that (inlined resource case) or do a REST request to lazily retrieve the State object (resource URI case, i.e. lazy) from the ID specified in the backing property.
Question
The issue is, this backing field is pretty ugly. What I would like is a way to have Castle generate a class that would have the backing property with the XmlElement attribute applied that I could pass to the XmlSerializer. Then my DTO classes could look more like the first example and wouldn't have to be aware that the actual serialising class has a backing property.
Is something like this possible with Castle or any other Proxy library?
After going an interesting and completely wrong way, i think it is indeed possible to create a backing field that won't be seen by clients. Since proxying works by inheriting from the proxied class, any property on the derived class won't be seen in the scope of the original class. So mixins are the way to go:
Given Foo
public class Foo
{
public virtual string Name { get; set; }
public virtual Bar bar { get; set; }
}
and Bar
public class Bar
{
public virtual string Name { get; set; }
}
We can declare an interface that will let us retrieve the backing field and an implementation
public interface IHasBarBackingField
{
Bar RetrieveBar();
}
public class HasBarBackingField : IHasBarBackingField
{
public HasBarBackingField()
{
// the constructor must contain ways to resolve the bar. Since
// the class is built while proxying you should have all the data
// available at this moment
}
public Bar RetrieveBar()
{
return new Bar(); // example, you could have a backing field somewhere in this class
}
}
Then you just have to mixin both classes when proxying:
var pg = new ProxyGenerator();
var hasBarBackingField = new HasBarBackingField();
var options = new ProxyGenerationOptions();
options.AddMixinInstance(hasBarBackingField);
var test = pg.CreateClassProxy<Foo>(options, new BarInterceptor());
and intercept the call interesting you in order to return the backing Bar
public class BarInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name == "get_bar")
{
var hasBarBackingField = invocation.InvocationTarget as IHasBarBackingField;
invocation.ReturnValue = hasBarBackingField.RetrieveBar();
}
else
{
invocation.Proceed();
}
}
}
The HasBarBackingField class should be built to return either the direct object or retrieve the referenced REST object. Hope this helps
Based on what i've seen NSubstitute do i'd say it is possible, as long as your properties are virtual: http://nsubstitute.github.io/help/partial-subs/ .
Creating a City class with virtual property State that is then resolved at runtime using the substitution pattern should be feasable
public class City
{
public string Name { get; set; }
[StateId(10)]
public virtual State State { get; set; }
}
var sCity = Substitute.For<City>();
sCity.State.Returns((core) => {return null; // here you can access informations about the call});
Definitely doable, but it's terra incognita from here on!
I have this code:
public string foo { get; set; }
Now, I interpret this as my object has a public property called foo, and both it's accessor's are public. If I write this:
private string foo { get; set; }
I interpret that as my object has a private property called foo, and both it's accessor's are private. I understand making the property itself private. What I don't understand is why the accessor's must be more restrictive? If I write:
private string foo { public get; public set; }
I interpret that my object has a private property called foo, and both's it's accessor's are public, which is the behavior that I want. I'd like the private property with public accessors. I mean, if I have to write a Get/Set method, I will. But I'm just confused as to why this is.
A property is actually (under water) nothing more than two methods:
public string foo { get; set; }
will translate into:
public string get_foo() { ... }
public void set_foo(string value) { ... }
These methods can only have ONE access modifier, not a combination of two.
If I remember correcly, C#v1 did not support access modifiers for the getters and setters. There was one access modifers for the property which was used for both functions.
In v2 it was possible to "override" one of getter/setter-pair, this way overrwriting the "other" function. There was no use to override both getters/setters, because in that would render the property-access modifier useless.
Why the access modifier for the getter/setter is more restrictive has, in my opinion, something to do with easier implementing interfaces which always have (implicitly public) properties.
For more info, read: http://msdn.microsoft.com/en-us/library/75e8y5dd(v=vs.80).aspx
Why you need such a property
private string foo { public get; public set; }
If you want to have you get set public, then make the property public.
The compiler will first check the access of the property and then its method. If the property is public then its method can have either public or private or any accessor
Take for example following code from a class:
public class Employee : IEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int EmployeeID { get; set; }
}
public class Company : IEntity
{
public string Name { get; set; }
public string TaxID { get; set }
}
I always used get; and set; with something in braces. I never left them like this.
Writing just:
get; set;
What it means?
Auto-Implemented Properties
In C# 3.0 and later, auto-implemented
properties make property-declaration
more concise when no additional logic
is required in the property accessors.
They also enable client code to create
objects. When you declare a property
as shown in the following example, the
compiler creates a private, anonymous
backing field that can only be
accessed through the property's get
and set accessors.
These are called Auto-Implemented Properties:
http://msdn.microsoft.com/en-us/library/bb384054.aspx
The compiler will generate a backing field, similar to this code:
public class Company : IEntity
{
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private string _Name;
}
It was decided that this syntax could be made much shorter, but still keep all the same utility, hence Auto-Implemented Properties were born :)
Just look at it as an quick and easy C# way of giving you a read write permission over a variable.
One of the good things of C# if you ask me.
The other answers pretty much tell you everything else there is to know about auto get set.
Even though these two quotes seem somewhat conflicting:
CD said:
In C# 3.0 and later, auto-implemented
properties make property-declaration
more concise when no additional logic
is required in the property accessors.
They also enable client code to create
objects. When you declare a property
as shown in the following example, the
compiler creates a private, anonymous
backing field that can only be
accessed through the property's get
and set accessors.
While Merlyn Morgan-Graham said:
These are called Auto-Implemented
Properties:
http://msdn.microsoft.com/en-us/library/bb384054.aspx
The compiler will generate a backing
field, similar to this code:
public class Company : IEntity {
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private string _Name; }
It was decided that this syntax could
be made much shorter, but still keep
all the same utility, hence
Auto-Implemented Properties were born
:)
To me that seems like CD said it does create a condition whilst Merlyn Morgan-Graham said there are none.
I think CD is correct when stating you can longer use , for example, the setters write permission as a response to also change whatever it's writing.
private int x = 3;
public int _x { get; set /*Change x*/; }
You would have to use the normal get set construction for that