C# unused Property crash my code - c#

The Code prints different answer depending on debugging or not. What did i wrong?
class Program
{
static void Main(string[] args)
{
Feld feld = new Feld();
feld.Setze = 5;
Console.WriteLine(feld.Besetzt);
Console.Read();
}
}
public class Feld
{
public int figur;
public bool Besetzt { get => (figur != 0) ? true : false; }
public int Setze { set => figur = value; }
public int Nehmen { get { int cur = figur; figur = 0; return cur; } }
}
If i delet the last Property it work's but why?

To expand on the existing comments and answers: your Nehmen property has nasty side-effects:
public int Nehmen { get { int cur = figur; figur = 0; return cur; } }
every time the value is read, it resets itself to zero. This is a very bad idea - property get accessors should not have unexpected side-effects. Large parts of the tooling expect reading Nehmen to not do that, and the IDE / debugger will often try to help you understand your data by querying the properties to show you.
This means that when the debugger is trying to help you, it is actually resetting the values.
So: make Nehmen a method:
public int Nehmen()
{
int cur = figur;
figur = 0;
return cur;
}
The system expects methods to have side-effects, so does not invoke them to "help" you.
The only valid side-effects of property get accessors is to invoke lazy-loading / initialization side effects.

You must have the variable Nehmen in the Watch Window in Visual Studio... Or trying to access it in other way

Related

Get and Set condition value

I'm trying to learn get and set and I can't seem to figure out this problem. I have a condition to set a value, only set the value if it's greater than "_num = 10".
My problem is, even if the value is under 10 the value still sets. What am I missing? I should get an error with this code, but I'm not getting it...
thanks for ur time.
using System;
namespace Namespace
{
internal class Program
{
private static void Main(string[] args)
{
int x = Items.Sum = 5;
Console.WriteLine(x);
Console.ReadKey();
}
}
public static class Items
{
private static int _num = 10;
public static int Sum
{
get { return _num; }
set
{
if (value > _num)
_num = value;
}
}
}
}
Because your have property as static and it will be set even before the constructor gets called. That’s why it is returning 10.
Please declare the main method as public not private.

How do I clear this list/array? Forms

I am making a To Do program in windows forms where I want to save events, what day/hour they happen and the priority.
I am filling a listbox with information, then I want to start over and have a clean slate. The listbox looks cleared but once another input is made all the old ones show up as well. I think this is because I havent cleared the list/array.
I've tried using Array.Clear(), but I dont know whether to make a new method for it or put it in my InitalizeGUI(). I also don't know if I am clearing a list or an array as it is a list to start with but is converted to a string array.
class TaskManager
{
private List<Task> todo;
public TaskManager()
{
todo = new List<Task>();
}
public Task GetItem (int index)
{
if (!CheckIndex(index))
return null;
return todo[index];
}
public int Count
{
get { return todo.Count; }
}
public bool AddItem (Task itemIn)
{
bool ok = false;
if (itemIn != null)
{
todo.Add(itemIn);
ok = true;
}
return ok;
}
private bool CheckIndex (int index)
{
return(index >= 0) && (index < todo.Count);
}
public string [] ListToStringArray()
{
string[] taskArray = new string[Count];
for (int i = 0; i < Count; i++) taskArray[i] = todo[i].ToString();
return taskArray;
}
}
}
This is my Taskmanager class. Do i make a method to clear this list/array, and should it be made in TaskManager or Mainform?
I've tried all the ways I could from googling online but I can't figure it out.
Hopefully someone knows how to help!
Best regards
Add a new public method in TaskManager class that clears the 'todo' private variable.:
public void ClearList()
{
todo.Clear();
}
Call it when you need your list empty. Eg.: At the InitGui() method.

Why does using delegates in c# give a stackoverflowexception

When I came across delegates I wrote this really simple program just to practice. when I run it there is a stackoverflowexception. so if anyone can tell me what is wrong with this piece of code please do cause I have wasted a lot of time on trying to make it work but couldn't.
Here is the code:
using System;
public delegate void click();
class test
{
public click flare;
public double length;
public double Length
{
get
{
return Length;
}
set
{
Length = value;
flare();
}
}
}
class glance
{
public glance(ref test a)
{
a.flare = blank;
}
public void blank()
{
Console.WriteLine("this is blank");
}
}
class Program
{enter code here
static void Main(String[] args)
{
test know = new test();
glance x = new glance(ref know);
know.Length = 10;
}
}
It has nothing to do with delegates. You are calling setter method inside of setter in Lenght property and that causes the exception.Use the backing field you created for your property:
public double Length
{
get
{
return length;
}
set
{
length = value;
flare();
}
}

What is a best practice for making a class's properties thread safe?

[Edit: It looks like the original question involved a double and not an integer. So I think this question stands if we change the integer to a double.]
I have rare issue with reading integer properties from a class used in multiple threads that sometimes returns a zero value. The values are not changed after initialization.
This question addresses that. The consensus is that even though I'm accessing an integer I need to synchronize the properties. (Some of the original answers have been deleted). I haven't chosen an answer there because I have not resolved my issue yet.
So I’ve done some research on this and I’m not sure which of .Net 4’s locking mechanisms to use or if the locks should be outside the class itself.
This is what I thought about using:
public class ConfigInfo
{
private readonly object TimerIntervalLocker = new object();
private int _TimerInterval;
public int TimerInterval
{
get
{
lock (TimerIntervalLocker) {
return _TimerInterval;
}
}
}
private int _Factor1;
public int Factor1
{
set
{
lock (TimerIntervalLocker) {
_Factor1 = value;
_TimerInterval = _Factor1 * _Factor2;
}
}
get
{
lock (TimerIntervalLocker) {
return _Factor1;
}
}
}
private int _Factor2;
public int Factor2
{
set
{
lock (TimerIntervalLocker) {
_Factor2 = value;
_TimerInterval = _Factor1 * _Factor2;
}
}
get
{
lock (TimerIntervalLocker) {
return _Factor2;
}
}
}
}
But I’ve read that this is horribly slow.
Another alternative is to lock the instance of ConfigData on the user side but that seems to be a lot of work. Another alternative I’ve seen is Monitor.Enter and Monitor.Exit but I think Lock is the same thing with less syntax.
So what is a best practice for making a class's properties thread
safe?
a. Using lock can be slow since it uses operating system resources, if the properties' complexity is low, then spin lock (or interlocked.compareexchange) will be faster.
b. You have to make sure that a thread won't enter a lock and via a call from one property to another get locked out. - If this can happen (non currently an issue in your code), you'll need to make the lock thread or task sensitive.
Edit:
If the object is supposed to be set during initialization and never changed, make it immutable (like .NET strings are). Remove all the public setters and provide a constructor with parameters for defining the initial state and perhaps additional methods/operators for creating a new instance with a modified state (e.g. var newString = "Old string" + " was modified.";).
If the values never change, it would be easier to just make a copy of that instance and pass each thread an instance of it's own. No locking required at all.
I think you should rewrite your ConfigInfo class to look like this; then you can't get overflow or threading problems:
public sealed class ConfigInfo
{
public ConfigInfo(int factor1, int factor2)
{
if (factor1 <= 0)
throw new ArgumentOutOfRangeException("factor1");
if (factor2 <= 0)
throw new ArgumentOutOfRangeException("factor2");
_factor1 = factor1;
_factor2 = factor2;
checked
{
_timerInterval = _factor1*_factor2;
}
}
public int TimerInterval
{
get
{
return _timerInterval;
}
}
public int Factor1
{
get
{
return _factor1;
}
}
public int Factor2
{
get
{
return _factor2;
}
}
private readonly int _factor1;
private readonly int _factor2;
private readonly int _timerInterval;
}
Note that I'm using checked to detect overflow problems.
Otherwise some values will give incorrect results.
For example, 57344 * 524288 will give zero in unchecked integer arithmetic (and there's very many other pairs of values that will give zero, and even more that will give a negative result or a positive value that "seems" correct).
It is best, as mentioned in the comments, to make the properties readonly. I thought about the following possibility:
public class ConfigInfo
{
private class IntervalHolder
{
public static readonly IntervalHolder Empty = new IntervalHolder();
private readonly int _factor1;
private readonly int _factor2;
private readonly int _interval;
private IntervalHolder()
{
}
private IntervalHolder(int factor1, int factor2)
{
_factor1 = factor1;
_factor2 = factor2;
_interval = _factor1*_factor2;
}
public IntervalHolder WithFactor1(int factor1)
{
return new IntervalHolder(factor1, _factor2);
}
public IntervalHolder WithFactor2(int factor2)
{
return new IntervalHolder(_factor1, factor2);
}
public int Factor1
{
get { return _factor1; }
}
public int Factor2
{
get { return _factor2; }
}
public int Interval
{
get { return _interval; }
}
public override bool Equals(object obj)
{
var otherHolder = obj as IntervalHolder;
return
otherHolder != null &&
otherHolder._factor1 == _factor1 &&
otherHolder._factor2 == _factor2;
}
}
private IntervalHolder _intervalHolder = IntervalHolder.Empty;
public int TimerInterval
{
get { return _intervalHolder.Interval; }
}
private void UpdateHolder(Func<IntervalHolder, IntervalHolder> update)
{
IntervalHolder oldValue, newValue;
do
{
oldValue = _intervalHolder;
newValue = update(oldValue);
} while (!oldValue.Equals(Interlocked.CompareExchange(ref _intervalHolder, newValue, oldValue)));
}
public int Factor1
{
set { UpdateHolder(holder => holder.WithFactor1(value)); }
get { return _intervalHolder.Factor1; }
}
public int Factor2
{
set { UpdateHolder(holder => holder.WithFactor2(value)); }
get { return _intervalHolder.Factor2; }
}
}
This way, your TimerInterval value is always in sync with its factors. The only problem is when some thread reads one of the properties while another writes them from outside the ConfigInfo. The first one could get wrong value and I don't see any way to solve this without introducing a single lock root. The question is whether read operations are critical.

C# Locking, Properties & Permissions

I've been using lock on value type properties when multi-threaded access is required. Also, I've been meaning to become more diligent about applying proper access modifiers, especially in my library code that is starting to become useful in multiple projects. I've written some code and would like to request comments on the various strategies in it for properties and locking the member variables they wrap. Thanks.
using System;
public class Program
{
static void Main(string[] args)
{
SomeValueType svt = new SomeValueType();
SomeReferenceType srt = new SomeReferenceType();
PermissionsAndLocking p = new PermissionsAndLocking(5, svt, srt);
//Invalid.
//p.X = 6;
//Invalid
//p.Svt = new SomeValueType();
//Invalid
//p.Svt.X = 1;
//Valid, but changes a copy of p.Svt because Svt is a value type.
SomeValueType svt2 = p.Svt;
svt2.X = 7;
//Invalid
//p.Srt = new SomeReferenceType();
//Valid, change the member data of p.Srt.
p.Srt.X = 8;
SomeReferenceType srt2 = p.Srt;
srt2.X = 9;
Console.WriteLine("Press the any key.");
Console.Read();
}
}
public class PermissionsAndLocking
{
//_x cannot be changed outside the class.
//_x cannot be changed "at the same time" it is being accessed???
private readonly object _xLock = new object();
private int _x;
public int X
{
get
{
lock (_xLock)
{
return _x;
}
}
private set
{
lock (_xLock)
{
_x = value;
}
}
}
//_svt and its members cannot be assigned to outside the class.
//_svt cannot be changed "at the same time as" it is being accessed.
private readonly object _svtLock = new object();
private SomeValueType _svt;
public SomeValueType Svt
{
get
{
lock (_svtLock)
{
return _svt;
}
}
private set
{
lock (_svtLock)
{
_svt = value;
}
}
}
//private on set works for = but member data can still be manipulated...
//Locking isn't complete because the reference is returned and can be accessed at a later time???
private readonly object _srtLock = new object();
private SomeReferenceType _srt;
public SomeReferenceType Srt
{
get
{
lock (_srtLock)
{
return _srt;
}
}
private set
{
lock (_srtLock)
{
_srt = value;
}
}
}
public PermissionsAndLocking(int x, SomeValueType svt, SomeReferenceType srt)
{
_x = x;
_svt = svt;
_srt = srt;
}
}
public struct SomeValueType
{
public int X;
}
public class SomeReferenceType
{
public int X;
}
You need to read about multi-threading and concurrency. Locking is about protecting invariants whilst they are invalid, i.e., while an invariant is invalid, prevent concurrent access to the shared memory that the invariant is dependant upon. The first step is to understand what invariant your code routine has, and secondly, within which block of code is the invariant invalid.
For example, a property getter has no intrinsic need to be synchronized with a lock. It only reads the property value. What invariant is invalid while this read is going on ? An operation that reads the variable, increments it, and then writes the incremented value back to the property might need to be locked, but locking the individual getter and setter would be totally inadequate. The entire operataion, including the read and the write, would have to be inside the protected block.
You should always lock a static object, so you should mark _svtLock as static in order for the lock to have an effect.
_x cannot be changed outside the class. True. It must be changed via X.
If you implement lock correctly ( see 1), then _x can't be changed at the time it's accessed.

Categories

Resources