Unexpected behavior with Struct internal values - c#

*Solved. Thanks for the explanations guys, I didn't fully understand the implications of using a value type in this situation.
I have a struct that I'm using from a static class. However, the behavior is showing unexpected behavior when I print it's internal state at runtime. Here's my struct:
public struct VersionedObject
{
public VersionedObject(object o)
{
m_SelectedVer = 0;
ObjectVersions = new List<object>();
ObjectVersions.Add(o);
}
private int m_SelectedVer;
public int SelectedVersion
{
get
{
return m_SelectedVer;
}
}
public List<object> ObjectVersions;//Clarifying: This is only used to retrieve values, nothing is .Added from outside this struct in my code.
public void AddObject(object m)
{
ObjectVersions.Add(m);
m_SelectedVer = ObjectVersions.Count - 1;
}
}
Test code
VersionedObject vo = new VersionedObject(1);
vo.AddObject(2);//This is the second call to AddObject()
//Expected value of vo.SelectedVerion: 1
//Actual value of vo.SelectedVersion: 1
Now, if you test this code in isolation, i.e., copy it into your project to give it a whirl, it will return the expected result.
The problem; What I'm observing in my production code is this debug output:
objectName, ObjectVersions.Count:2, SelectedVer:0,
Why? From my understanding, and testing, this should be completely impossible under any circumstances.
My random guess is that there is some sort of immutability going on, that for some reason a new struct is being instanced via default constructor, and the ObjectVersions data is being copied over, but the m_SelectedVersion is private and cannot be copied into the new struct?
Does my use of Static classes and methods to manipulate the struct have anything to do with it?
I'm so stumped I'm just inventing wild guesses at this point.

Struct is value type. So most likely you are creating multiple copies of your object in your actual code.
Consider simply changing struct to class as content of your struct is not really good fit for value type (as it is mutable and also contains mutable reference type).
More on "struct is value type":
First check FAQ which have many good answers already.
Value types are passed by value - so if you call function to update such object it will not update original. You can treat them similar to passing integer value to function: i.e. would you expect SomeFunction(42) to be able to change value of 42?
struct MyStruct { public int V;}
void UpdateStruct(MyStruct x)
{
x.V = 42; // updates copy of passed in object, changes will not be visible outside.
}
....
var local = new MyStruct{V = 13}
UpdateStruct(local); // Hope to get local.V == 42
if (local.V == 13) {
// Expected. copy inside UpdateStruct updated,
// but this "local" is untouched.
}

Why is this a struct and not a class? Even better, why are you tracking the size of the backing store (List<T>) rather than letting the List<T> track that for you. Since that underlying backing store is public, it can be manipulated without your struct's knowledge. I suspect something in your production code is adding to the backing store without going through your struct.
If it were me, I'd set it up something like this, though I'd make it a class...but that's almost certainly a breaking change:
public struct VersionedObject
{
public VersionedObject()
{
this.ObjectVersions = new List<object>() ;
return ;
}
public VersionedObject(object o) : this()
{
ObjectVersions.Add(o);
return ;
}
public VersionedObject( params object[] o ) : this()
{
ObjectVersions.AddRange( o ) ;
return ;
}
public int SelectedVersion
{
get
{
int value = this.ObjectVersions.Count - 1 ;
return value ;
}
}
public List<object> ObjectVersions ;
public void AddObject(object m)
{
ObjectVersions.Add(m);
return ;
}
}
You'll note that this has the same semantics as your struct, but the SelectedVersion property now reflects what's actually in the backing store.

Related

Equivalent (or better) C# structures to C++ structures

I am a C++ programmer moving to C# (so complete newb really). So far its a pretty easy transition :)
I am porting some code (well, re-writing it) from C++ to C#. I am stuck with lots of possibilities on how to port the following C++ STL structures. Here is a C++ code snippet of my C++ structure layout (I have not bothered showing the enums to save on clutter, but I can add if required):
struct DeviceConnection_t
{
DeviceType_e device;
DeviceState_e state;
bool isPass;
DeviceConnection_t() :
device(DEV_TYPE_UNKNOWN),
state(DEV_STATE_DISCONNECTED),
isPass(false)
{}
};
struct Given_t
{
std::string text;
std::vector<DeviceConnection_t> deviceConnections;
};
struct Action_t
{
ActionEventType_e type;
uint32_t repeat_interval;
uint32_t repeat_duration;
DeviceType_e device;
bool isDone;
Action_t() :
type(AE_TYPE_UNKNOWN),
repeat_interval(0),
repeat_duration(0),
device(DEV_TYPE_UNKNOWN),
isDone(false)
{}
};
struct When_t
{
std::string text;
std::multimap<uint32_t, Action_t> actions; // time, action
};
So here I have a vector of DeviceConnection_t, which I have read here: c-sharp-equivalent-of-c-vector-with-contiguous-memory can just be made into a C# List<DeviceConnection_t>. That seems to work, so far so good.
Next is my multimap<int, Action_t> where the int is a time value where duplicate entries are expected/allowed.
I read here: multimap-in-net that there is no equivalent in C#, but there are various implementations out there.
So I could use one of these, but other questions I read like: order-list-by-date-and-time-in-string-format got me thinking there might be a better way to achieve what I want.
What I really want is:
1.A list of Action_t in time order - where time could be an element of Action_t (I removed it as a element in my c++ because it became my multi-map key). I also need to be able to search through the collection to find time values.
2. Some sort of default constructor to populate the default values of a newly instantiated struct, but I can't see how this is done either.
I really like the look of the Dictionary C# class, but I don't think that fits any of my requirements at the moment (might be wrong here).
So my two questions are:
What is the best way to create a time ordered collection of objects?
How can I assign default values to a new instance of a structure? (in the same way a default constructor does in C++)?
By using struct, it is impossible to enforce initial values. No explicit default constructor can be provided and in case of default construction, all values will be initialized with their default value. It is only possible to provide additional constructors, where fields can be initialized. In the example, if AE_TYPE_UNKNOWN and DEV_TYPE_UNKNOWN would be 0, then default initialization would actually be equivalent to your values.
struct Action_t
{
// example constructor, but there will always be a default constructor
public Action_t(ActionEventType_e type, DeviceType_e device)
{
this.type = type;
this.device = device;
this.isDone = false;
this.repeat_interval = 0;
this.repeat_duration = 0;
}
public ActionEventType_e type;
public UInt32 repeat_interval;
public UInt32 repeat_duration;
public DeviceType_e device;
public bool isDone;
}
If you need to enforce initialization with values that differ from the default, then you need to create a class, where explicit initialization is possible.
class Action_t
{
public ActionEventType_e type = ActionEventType_e.AE_TYPE_UNKNOWN;
public UInt32 repeat_interval = 0;
public UInt32 repeat_duration = 0;
public DeviceType_e device = DeviceType_e.DEV_TYPE_UNKNOWN;
public bool isDone = false;
}
However, for more flexibility I'd advice to use public properties, either as auto properties or as public properties with private backing field. Depending on your choice and used language standard version, you have different options how to write the properties and the initialization:
class Action_t
{
public Action_t()
{
repeat_interval = 0;
}
public UInt32 repeat_interval { get; set; }
private UInt32 _repeat_duration = 0;
public UInt32 repeat_duration
{
get { return _repeat_duration; }
set { _repeat_duration = value; }
}
public bool isDone { get; set; } = false; // valid for C# 6
}
You should read into the differences between struct and class in C#, since there are some mayor differences that you may not expect as a C++ programmer, where struct is basically a public-default class. Then decide, if struct is suited for your case.
The best equivalent to a sorted multimap would probably be a SortedDictionary<key, ICollection<values>> with an add method that handles new keys / adding to existing keys.
IDictionary<DateTime, ICollection<Action_t>> actions = new SortedDictionary<DateTime, ICollection<Action_t>>();
void AddAction(DateTime key, Action_t action)
{
ICollection<Action_t> values;
if (!actions.TryGetValue(key, out values))
{
values = new List<Action_t>();
actions[key] = values;
}
values.Add(action);
}
Unfortunately C# doesn't seem to have a sorted List. The Dictionary is fine if you have Key, Value pairs.
1) If its just a collection (List) you can take a look at the discussion here:
Is there a SortedList<T> class in .NET?. Otherwise you can manually sort the collection(I named it sort in my example) like:
actions.Sort((x, y) => x.time.CompareTo(y.time));
In this your time object should be a IComparable or a primitive, but you can replace "x.time.CompareTo" to any other sorting method. (Based on: List<> OrderBy Alphabetical Order).
If you use a list you can just search the collection with linq:
actions.First(x=>x.time.certainValue == DesiredValue);
But there are many functions to search through the tree. There are some displayed: https://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods(v=vs.110).aspx
2) There are multiple ways to do this. First off, the default constructor:
Action_t() {
type=AE_TYPE_UNKNOWN;
repeat_interval=0;
repeat_duration=0;
device= DEV_TYPE_UNKNOWN);
isDone = false;
}
This works like any other code. But if all values are public Properties (Also a variable: https://msdn.microsoft.com/nl-nl/library/x9fsa0sw.aspx) then you can remove the constructor (or have a public one that you can access) and create new instances with:
new Action_t {
type=AE_TYPE_UNKNOWN,
repeat_interval=0,
repeat_duration=0,
device= DEV_TYPE_UNKNOWN),
isDone = false
}
The difference is where the variables are set. The default constructor is always safe.
I hope this answers your question!

Link Two Properties/Variables

Let me explain my situation. I have a program who reads an external connection and gives me an array of integers (or booleans). Those inputs should feed an object that has some properties (X, Y, Z, for example). So, if a read a value on array, i should write those values in the properties. Is there a way to pass those values by ref (for example) ? Thinking logically , the best way way would be pointers (property X pointing to array[0]), but these aren't very unclear to me.
I can create a way to look for changes in array (but is a very large array, +60000), then update my object. But i think this would be a bad ideia.
Sorry if i wrote any crap, i'm just starting on C#.
Some pseudo code to help.
class obj
{
int X {get; set;}
public obj(ref int x)
{
X = x;
}
}
class main
{
void main()
{
int a;
obj test = new obj(ref a);
}
}
So if: a = 10, obj.X = 10 too.
public class MyClass
{
private int[] backingArray;
public int X
{
get
{
if (backingArray == null)
return -1;
else
return backingArray[0];
}
}
public MyClass(int[] array)
{
if (array.Length > 0)
backingArray = array;
}
}
class Main
{
void Main()
{
int[] array = new int[] { 2 };
MyClass test = new MyClass(array);
array[0] = 6;
Console.WriteLine(test.X);//prints 6
}
}
Of course this only works with reference types (arrays are reference types). If you wanted to do this whole thing with a value type, you'd need to "wrap" it in some reference type. You can use a class such as the following to wrap anything if you don't have anything convenient.
public class Wrapper<T>
{
public T Value { get; set; }
}
It's not possible to use ref in the manor that you've shown in the OP. You wouldn't be able to store the value that was passed by reference. If you could, then you could end up passing some value on the stack and then having the created object that holds the reference living longer than the item on the stack. If that happened you would end up with a reference it a location in memory that no longer holds the variable you intended. This was somewhat of a gotcha in C++ that the designers of C# went out of their way to ensure can't happen (at least not without a lot of work).

How to set a specific member of a struct, using indexing in C#

Assuming I have a struct:
struct Vector
{
public int X, Y;
// ...
// some other stuff
}
and a class:
class Map
{
public Vector this[int i]
{
get
{
return elements[i];
}
set
{
elements[i] = value;
}
}
private Vector[] elements
// ...
// some other stuff
}
I want to be able to do something like: map[index].X = 0; but I can't, because the return value is not a variable.
How do I do this, if at all possible?
You should avoid mutable structs.
If you want your type to be mutable use a class instead.
class Vector
{
public int X { get; set; } // Use public properties instead of public fields!
public int Y { get; set; }
// ...
// some other stuff
}
If you want to use a struct, make it immutable:
struct Vector
{
private readonly int x; // Immutable types should have readonly fields.
private readonly int y;
public int X { get { return x; }} // No setter.
public int Y { get { return y; }}
// ...
// some other stuff
}
The compiler prevents you from doing this because the indexer returns a copy of an object not a reference (struct is passed by value). The indexer returns a copy, you modify this copy and you simply don't see any result. The compiler helps you avoid this situation.
If you want to handle such situation you should use class instead or change the way you deal with Vector. You shouldn't modify it's value but initialize it's values in constructor, more on this topic: Why are mutable structs “evil”?.
define Vector as class,
or
store value in a temporary variable
var v = map[index];
v.X = 0;
map[index] = v;
or
add function to change
map[index] = map[index].Offset()
or
let the [] operator return a setter class
class Setter { Vector[] Data; int Index; public double X { get { return Data[Index]; } set { Data[Index] = new Vector(value, Data[Index].Y); }}}
public Setter this[int i]
{
get
{
return new Setter() { Data = elements, Index= i };
}
}
Although generic classes work pretty well for many purposes, they do not provide any reasonable way to access structs by reference. This is unfortunate since in many cases a collection of structs would offer better performance (both reduced memory footprint and improved cache locality) and clearer semantics than a collection of class objects. When using arrays of structs, one can use a statement like ArrayOfRectangle[5].Width += 3; with very clear effect: it will update field X of ArrayOfRectangle[5] but it will not affect field X of any other storage location of type Rectangle. The only things one needs to know to be certain of that are that ArrayOfRectangle is a Rectangle[], and Rectangle is a struct with a public int field X. If Rectangle were a class, and the instance held in ArrayOfRectangle[5] had ever been exposed to the outside world, could be difficult or impossible to determine whether the instance referred to by ArrayOfRectangle[5] was also held by some other code which was expecting that field X of its instance wouldn't change. Such problems are avoided when using structures.
Given the way .net's collections are implemented, the best one can do is usually to make a copy of a struct, modify it, and store it back. Doing that is somewhat icky, but for structs that aren't too big, the improved memory footprint and cache locality achieved by using value types may outweigh the extra code to explicitly copy objects from and to the data structures. It will almost certainly be a major win compared with using immutable class types.
Incidentally, what I'd like to see would be for collections to expose methods like:
OperateOnElement<paramType>(int index, ref T element, ref paramType param, ActionByRef<T,paramType> proc) which would call proc with the appropriate element of the collection along with the passed-in parameter. Such routines could in many cases be called without having to create closures; if such a pattern were standardized, compilers could even use it to auto-generate field-update code nicely.

Encapsulation questions in C#

I'm having some problems with encapsulation in C#. There are two specific scenarios that are causing me problems and I believe the issue is related.
Scenario #1
I have a class definition that looks something like this
class MyClass
{
private int _someField;
private OtherClass _otherClass;
public int someField
{
get { return _someField; }
set { _someField = value; }
}
public OtherClass otherClass
{
get { return _otherClass; }
set { _otherClass = value; }
}
}
If I then try and do something like this in a new piece of code
MyClass theClass = new MyClass();
theClass.otherClass.XYZ += 1;
I get told Cannot Modify the return value of 'MyClass.otherClass' because it is not a variable.
Scenario 2#
public partial class trksegType
{
private wptType[] trkptField;
private extensionsType extensionsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("trkpt")]
public wptType[] trkpt
{
get
{
return this.trkptField;
}
set
{
this.trkptField = value;
}
}
}
If I now try and foreach through the wptType array:
foreach (wptType way in trk.trkseg[i])
I get told - foreach statement cannot operate on variables of type 'trksegType' because 'trksegType' does not contain a public definition for 'GetEnumerator'
Even though an array should implicitly allow enumeration.
Can anyone explain what's going on and what I can do to get around this problem, whilst still maintaining best practices.
For scenario 1, I suspect that OtherClass has been defined as a struct. When a struct is accessed from a property accessor a new copy of the struct is created and returned (structs are value types). Changing a property on this new copy will have no effect on the original struct.
The C# compiler detects this and raises that slightly obscure error.
Scenario 1:
The reason is very likely because your OtherClass is a struct and not a class. Value sematics are a bit tricky and mutable value types are considered harmful. So you either want to make OtherClass a class and not a struct or you do something along those lines:
struct OtherClass
{
public int XYZ { get; }
public OtherClass(int xyz)
{
XYZ = xyz;
}
public OtherClass AddToXYZ(int count)
{
return new OtherClass(this.XYZ + count);
}
}
Then you can do
myClass.otherClass = myClass.otherClass.AddToXYZ(1);
Scenario 2:
You either need to implement IEnumerable on trksegType to enumerate over trkpt or actually access trkpt for the enumeration.
In General:
You have violated encapsulation in both scenarios by accessing objects through other objects. Have a look here: http://www.csharp-station.com/Tutorials/lesson19.aspx
You also should consider using better (more explicit) names for your objects. mttng vwls ds nt ncrs rdblty.
(You really shouldn’t post two questions in one.)
Scenario 1
Cannot Modify the return value of 'MyClass.otherClass' because it is not a variable.
This error happens because OtherClass is not a class, but a struct — also called a value type. This means that accessing MyClass.otherClass copies the value instead of returning a reference. You would be modifying this copy, which would be pointless. The compiler catches this because it is always a bug and never useful.
Scenario 2
foreach (wptType way in trk.trkseg[i])
You haven’t told us what trkseg[i] is, but if it is of the type trksegType, then the answer is: because trksegType doesn’t allow any enumeration. It does not implement IEnumerable, IEnumerable<T>, nor does it have a GetEnumerator method of its own.
Perhaps you meant to write:
foreach (wptType way in trk.trkseg[i].trkpt)
because trkpt is an array of wptType. (You might have found this error sooner if you used more meaningful variable names instead of weird combinations of letters that make no sense.)
I can't see anything wrong with your first example - so double check that the sample that errors really does and correct if not.
In the second instance, it looks like you're trying to iterate on an instance of trksegType, rather than the contained trkpt property. Try foreach (wptType way in trk.trkseg[i].trkpt) instead.

Empty accessors do matter? Regarding value types and their modification

I have following code that does not work due to "a" being a value typed. But I thought it would not work even without accessors, but it did:
class Program
{
a _a //with accessors it WONT compile
{
get;
set;
}
static void Main(string[] args)
{
Program p = new Program();
p._a.X = 5; //when both accessors are deleted, compiler does not
//complain about _a.X not being as variable
}
}
struct a
{
public int X;
}
It does not work as "a" is struct. But when I delete accessors from "_a" instance, it works. I do not understand why.
Thanks
The main feature of value types is that they are copied rather than being passed by reference.
When you have a value type, and an accessor, you essentially have a value type being returned from a method, which causes a copy (the following two examples are the same):
ValueType Property { get { return x; } } // Will make a copy of x
ValueType Method() { return x; } // Will make a copy of x
If you now assign to the returned value, you're assigning to a copy of x. So any changes made to the value returned from the property will be immediately lost.
When you remove the { get; } accessor, you've now got a basic field, e.g.:
int field;
or
ValueType field;
Which means no copy is made, which means when assigning to the field, you're no longer assigning to a copy.
The reason p._a.X = 5; won't work is because p._a returns a value of the type a. Values cannot change. But if you put the value in a variable, you may change the value of the variable.
You can't delete both accessors.
This way:
a _a;
it works, but it's not a property any more.
Edit: With a property, the value you get from p._a is a result of a function call. If you even modify it, the modified value will by no means "written back" to the "original" _a. Instead, you will just modify a temporary, returned by the getter-function.
C# could allow this, but it would lead to confusion, since people would expect that after p._a.X = 5; int xx = p._a.X; the value of xx would be 5. But it won't be so. Because p_.a is indeed not a variable :-)
The difference is that with
a _a;
your _a is a field; in case of
a _a { get; set; }
_a is a property. And the case
a _a { }
is not allowed.

Categories