I am working on some software that should be used for a special type of experiment.
The experiments are performed using:
1) A "Chip" (basically an XY grid of known dimensions).
2) Each Chip contains "Electrodes", identified by their X and Y coordinate on the chip and by a unique ID. Each electrode can also hold or not hold a sample, indicated by a simple bool (it's a biosensing chip).
I have objects that represent this hardware in C#.
I now need to use the hardware in an experiment;
1) I have an "Experiment" which exposes an IEnumerable holding "ExperimentStep" objects.
2) An "ExperimentStep" holds a name, and a limited list of "Electrodes" involved among other things.
Some experiment steps could run concurrently and could change the "HasSample" property of an electrode. Therefore, when I perform an "ExperimentStep" it might be good to know what the initial "HasSample" property is at any one time.
This is where my problem lies;
If I just pass "Electrode" objects to my "ExpermentStep" they will probably be passed by Value... Is it possible to create an IEnumerable that holds references to the unique electrodes so that each time I want to run an "ExperimentStep" the list of "Electrodes" used in that step holds the most recent value for "HasSample"? Should I use pointers for this?? From my limited knowledge of C++ I would expect that this would be trivial in that language (since you work with pointers most of the time). But in C# I really have no clue (and I am not experienced enough).
In c# a class is reference type. This means that if you create list of instances of a class and then also add the instances to another list then its the same items. Each list will hold a reference. So to that effect yes you can up the items using an IEnumberable.
I suspect you don't understand the difference between reference types and value types, and what pass by value really means in C#.
Assuming Electrode is a class, you can modify the properties of an instance of it and those changes will be visible via any reference to the same object.
I strongly recommend you make sure you have a firm understanding of the .NET type system before trying to develop a lot of production code. The consequences of not understanding what's going on can be disastrous.
A couple of my articles on these topics:
Reference types and value types in .NET
Parameter passing in C#
... but I suggest you get a good introductory C# book as well.
Related
There is a simulator. In this simulator we have to pass a corridor. In the corridor there is a door and a puzzle, the solution of which opens this door. As soon as we solve the puzzle, the value of the boolean attribute of the class (something like isOpen) changes to true
This corridor needs to be traversed several times. The corridor itself doesn't change, but the puzzle is random each time.
So, I decided to create a macro application that reaches the puzzle and waits until I solve it
And since the simulation has the boolean variable I need, I was wondering: can I get it, in order to then create a delay in the macro until it is true?
The main problem here is that the two programs are not connected in any way.
I also want to note that I have an understanding that all variables lose their names after compilation, and that variable values subsequently occupy a random place in memory
Also, I have experience with programs like CheatEngine, which is to find the address of a value by its value
But I may just not know all the details, thinking that it's impossible, even if in reality there are ways to do it.
For this reason, I would appreciate it if you could explain to me how this can be done, or, if it is not possible, explain why.
Also, I wouldn't mind a response like "Read this "
I understand that you want to inspect one or more properties of an instance of an object at runtime and this can be achieved by using the so-called Reflection.
The latter provides functionalities that allow you to examine objects at runtime, get their Type, read their properties and invoke their methods. It should be used carefully.
Using reflection you can do
// retrieves the value of the property "NameOfProperty" for the instance of object myobj
bool myFlag = myobj.GetType().GetProperty("NameOfProperty").GetValue(myobj, null);
i am building a sort of program that generates a random list of word according to a database.
I Made a class that deals with the word selecting and handling (a random select function, a connect to the database function etc..)
I have 3 variables that indicate the last 3 words chosen.
how do I use a funcion on the form1 (button 1 press), to manipulate the same 3 variables, without creating them from scratch everytime (what happens now...)
To make myself clearer:
accualy what I need is to know how to keep track of a variable between multiple classes.
I might be using the whole classes thing wrong... I am now triyng to get the grasp of it.
Thank you very much,
Barak.
Your two options as I see it are:
1) an instance of a class that holds those variables that can be passed around
You may want to use the singleton pattern for this class if you want to make sure there is only ever one of them.
2) A static class with static members holding this information.
It may be that your entire random word class could be static. In this case you'd just call the methods and properties on that class to generate and access your words.
Also I would suggest that you may want to consider a collection to hold your words rather than three separate variables. It will of course depend on your implementation so I will mention it just inc ase you haven't thought of it and I'm not saying you definitely should. :)
I would avoid static or Singletons just for this purpose - they're not good habits to pick up for simple object oriented scenarios.
Encapsulate the state variables in a class, which you instantiate first, then pass by reference into the form and/or data fetch logic.
Key to this is understanding the concept of reference - your form and fetch logic will see the same instance of your state class, effectively sharing it.
If you implement the "variables" as properties on the state class, you can use events to notify other parts of your code when the word states change.
Consider also clearly defining the possible interactions (interfaces) on the state class. One aspect seems to be to add a word, another to pull out statistics based on the added words. The state class can accommodate all this, and provide a nice place for future extensions.
Try to think in terms of public interface methods/properties, while keeping "variables" (i.e. fields like counters or collections) private.
I also agree that your post should be improved with snippets of actual code - help us helping you.
And I hope your code is not being used to generate spam mails/posts... :-)
Why do we need reference types in .NET?
I can think of only 1 cases, that it support sharing data between different functions and hence gives storage optimization.
Other than that I could not enumerate any reason, why reference types are needed?
Why do we need reference types in .NET? I can think of only one reason: that it support sharing of data and hence gives storage optimization.
You've answered your own question. Do you need a better reason than that?
Suppose every time you wanted to refer to the book The Hobbit, you had to instead make a copy of the entire text. That is, instead of saying "When I was reading The Hobbit the other day...", you'd have to say "When I was reading In a hole in the ground there lived a hobbit... [all the text] ... Well thank goodness for that, said Bilbo, handing him the tobacco jar. the other day..."
Now suppose every time you used a database in a program, instead of referring to the database, you simply made a full copy of the entire database, every single time you used any of it in any way. How fast do you think such a program would be?
References allow you to write sentences that talk about books by use of their titles instead of their contents. Reference types allow you to write programs that manipulate objects by using small references rather that enormous quantities of data.
class Node {
Node parent;
}
Try implementing that without a reference type. How big would it be? How big would a string be? An array? How much space would you need to reserve on the stack for:
string s = GetSomeString();
How would any data be used in a method that wasn't specific to one call-path? Multi-threaded code, for example.
Three reasons that I can think of off the top of my head.
You don't want to continually copy objects every time you need to pass them to a Method or Collection Type.
When iterating through collections, you may want to modify the original object with new values.
Limited Stack Space.
If you look at value types like int, long, float you can see that the biggest type store 8 bytes or 64 bits.
However, think about a list or an array of long values, in that case, if we have a list of 1000 values then the worst case will take 8000 bytes.
Now, to pass by value 8000 bytes will make our program to run super slow, because the function that took the list as a parameter will now have to copy all these values into a new list and by that we loose time and space.
That's why we have reference types, because if we pass that list then we don't lose time and space to copy that list because we pass the address of the list in the memory.
The reference type in the function will work on the same address as the list you passed, and if you want to copy that list you can do that manually.
By using reference types we save time and space for our program because we don't bother to copy and save the argument we passed.
`I need to know if two references from completely different parts of the program refers to the same object.
I can not compare references programaticaly because they are from the different context (one reference is not visible from another and vice versa).
Then I want to print unique identifier for each object using Console.WriteLine(). But ToString() method doesn't return "unique" identifier, it just returns "classname".
Is it possible to print unique identifier in C# (like in Java)?
The closest you can easily get (which won't be affected by the GC moving objects around etc) is probably RuntimeHelpers.GetHashCode(Object). This gives the hash code which would be returned by calling Object.GetHashCode() non-virtually on the object. This is still not a unique identifier though. It's probably good enough for diagnostic purposes, but you shouldn't rely on it for production comparisons.
EDIT: If this is just for diagnostics, you could add a sort of "canonicalizing ID generator" which was just a List<object>... when you ask for an object's "ID" you'd check whether it already existed in the list (by comparing references) and then add it to the end if it didn't. The ID would be the index into the list. Of course, doing this without introducing a memory leak would involve weak references etc, but as a simple hack this might work for you.
one reference is not visible from another and vice versa
I don't buy that. If you couldn't even get the handles, how would you get their ID's?
In C# you can always get handles to objects, and you can always compare them. Even if you have to use reflection to do it.
If you need to know if two references are pointing the same object, I'll just citate this.
By default, the operator == tests for
reference equality. This is done by
determining if two references indicate
the same object. Therefore reference
types do not need to implement
operator == in order to gain this
functionality.
So, == operator will do the trick without doing the Id workaround.
I presume you're calling ToString on your object reference, but not entirely clear on this or your explained situatyion, TBH, so just bear with me.
Does the type expose an ID property? If so, try this:
var idAsString = yourObjectInstance.ID.ToString();
Or, print directly:
Console.WriteLine(yourObjectInstance.ID);
EDIT:
I see Jon seen right through this problem, and makes my answer look rather naive - regardless, I'm leaving it in if for nothing else but to emphasise the lack of clarity of the question. And also, maybe, provide an avenue to go down based on Jon's statement that 'This [GetHashCode] is still not a unique identifier', should you decide to expose your own uniqueness by way of an identifier.
If you have an immutable list, you expect it to always return a reference to the same object when you ask for, say
list.get(0)
My question is, would you expect to be able to mutate the object and have the mutation reflected next time you get it from the list?
It depends on the context. In a general purpose library, all we should assume is that the list is immutable. Changes to the elements in the list would be reflected to all callers, as a direct consequence of returning the same reference each time.
However, if this is a specialized immutable tree (or whatever), and is documented as such then you would expect the items in the list to themselves be immutable, and it becomes a moot question.
The question if not about the immutability of the list, but about the immutability of the objects contained.
In fact, if you have reference types, the immutable entity in the list is the reference. This means that the reference will always be the same. Now whether the referenced object changes only depends on what kind of object it is. If the object is immutable (like, for instance, strings in both .NET and Java, or all value types in .NET), the object cannot change.
Otherwise, the object can change and all other references to the same object will see the changed state, since they hold a reference to the same instance. Therefore, as I wrote in the beginning, this is completely independent of the list (and whether it is immutable or not).
That's usually to be expected. The list is immutable, which means you cannot add or remove items in it or replace items entirely. If you want those items to be immutable you have to take care of that yourself. The list certainly can't stop you from mutating the object's state once you got a reference to it.
Yes.
I don't expect an immutable list to clone its objects when I get them, unless it is documented as doing so.
It really depends on the context in which you ask that question. Any experienced Java or C# developer knows that it's technically almost impossible to have a general "deep immutability" and therefore would not expect this. In C++, it's a very complex topic, so most developers probably also don't expect a dependable deep immutability. The D programming language, on the other hand, does have a language-level concept of transitive immutability, so a D programmer would probably expect it wherever it makes sense (which is quite often).
Suppose a repair shop wanted to keep a permanent append-only record of all the cars that had ever visited, so that as each car entered the owners could find out if it had been in the shop before. Which would be better:
Keep a permanent record of the VIN (Vehicle Identification Number) of each car
Make a duplicate of each car (which, because VINs must be unique, must have a different VIN from the original) and permanently store the duplicate cars.
Note that a car itself is a mutable object, but the identity of a car, expressed by the VIN, is immutable. It's entirely possible that a car which was blue when it visited the shop has since been painted red. Thus, even if one had the ability to easily locate any car given its VIN, a list of cars (VINs) and when they were in the shop would not allow one to determine e.g. how many blue cars were serviced last Thursday. On the other hand, if the purpose of the list is to let one know whether an incoming vehicle had been in the shop previously, the list of VINs is exactly what one would need. If instead of having the VINs, one had a collection of duplicate cars, then not only would the cost of creating and storing all those duplicate cars be far greater than the cost of storing the VINs, but the collection would be almost useless for the stated purpose (determining whether a particular car had visited previously).
Yes, knowing Java, for an "immutable" List<T> I wouldn't expect T to be immutable unless T was immutable. However, a reasonable implementation of, say, List<Date> would be to copy the Date each time. The problem is that Date is mutable and can be distinguished from other equal Dates.