How can fix System.StackOverflow Exception? - c#

I used 2 classes, and I need send/receive methods and variables. But when I make an instance of this class it gives me a System.StackOverflowException.
How can fix this problem?
This is my code:
class Setup1
{
Setup2 set2 = new Setup();
int a = 5;
public int myMethod();
{
set2.b = a + 10;
return set2.b;
}
}
class Setup2
{
Setup1 set1 = new Setup();
public int b = 0;
void Show()
{
MessageBox.Show(set1.myMethod());
}
}

You have an infinite recursion.
In the constructor of Setup2() you call the constructor of Setup1(). There you call the constructor of Setup2()and so on, infinitely. Your memory runs out, and your stack overflows.

It seems that you have cyclic constructor calling that leads to stack-overflow exception.

Related

C# unused Property crash my code

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

Do we need to lock to call a method c#

Say I have the following code
public class SomeClass
{
private int int_var = 0;
private Object lock_obj = new Object();
public void Setter(int new_val)
{
lock(lock_obj)
{
int_var = new_val;
}
}
public int Getter()
{
lock(lock_obj)
{
return int_var;
}
}
}
Now My question is can I call Setter in one thread and getter in another thread
someClass.Setter(32);
int x = someClass.Getter();
I am unsure if the variable someCLass will be corrupted when I call getter or setter in different thread.
thanks

Singleton - task inside constructor fails to start/ does not start asynchronically

I have a bit of weird problem that is hard to explain. I have singleton class where in the constructor I have to run a task to initialize some components/resources.
I used 2 implementation of singleton from C# in Depth and in one case everything is working fine, in another case - not.
Code is available below with some comments.
The main problem that for some reason task is not started in one case, when I am using static field with initialier and static contructor (class Test2).
I made some other tests and looks like with the implementation 2 task does not start asynchronically, but starts synchronically after waiting time.
Implementation one. everything is working as expected
public sealed class Test1
{
private static Test1 instance = null;
private static readonly object padlock = new object();
private Test1()
{
using (AutoResetEvent startEvent = new AutoResetEvent(false))
{
new Task(() => TaskThread(startEvent)).Start();
if (!startEvent.WaitOne(1000))
{
throw new Exception("ERROR");
}
}
}
public int Result()
{
return 10;
}
private void TaskThread(AutoResetEvent startEvent)
{
//I am initializing some stuff here
startEvent.Set();
}
public static Test1 Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Test1();
}
return instance;
}
}
}
}
Implementation 2, task is never started, or started after waiting time of an event
public sealed class Test2
{
private static readonly Test2 instance = new Test2();
static Test2()
{
}
private Test2()
{
using (AutoResetEvent startEvent = new AutoResetEvent(false))
{
new Task(() => TaskThread(startEvent)).Start();
//here it fails to wait successfully and throws an
//exception. Time limit is not reached
if (!startEvent.WaitOne(1000))
{
throw new Exception("ERROR");
}
}
}
public int Result()
{
return 20;
}
private void TaskThread(AutoResetEvent startEvent)
{
//I am initializing some stuff here as well
//but in this implementation code is never reached
startEvent.Set();
}
public static Test2 Instance
{
get
{
return instance;
}
}
}
I am curious why is this happening and how to avoid this problems in future. Thanks a lot!
The root cause of such 'strange' behavior is pretty simple - CLR executes static constructor under a lock. That prevents created thread from entering TaskThread() method and setting startEvent to signaled state.
After you face with such a problem and puzzle for several hours why this is happening, you start to understand why many sources advise not to use doubtful constructs like static constructors, global variables, etc.

Retain local variable across method calls

Is there a way in C# to have a method retain a variable across different calls? For example:
private void foo()
{
int j; //declare this so as it isn't destroyed with the stack frame.
int i = calculateSomeValue() + j;
j = i;
}
The normal way I would do this would be with a member variable like this:
private int j = 0;
private void foo()
{
int i = calculateSomeValue() + j;
j = i;
}
I don't like how the variable j can be accessed in all of the other methods of the class. Plus it just seems messy this way: defining a member variable when it will only be used in one method to keep track of the value of i when the method was last called.
Is this possible in a nice/clean way? Or should I just use the member variable way and forget about it?
You could use a tiny little nested class to encapsulate it, along these lines:
public class Test
{
private int foo()
{
return nested.foo();
}
private int calculateSomeValue()
{
return 42;
}
readonly Nested nested = new Nested();
private class Nested
{
private int j;
public int foo()
{
int i = calculateSomeValue() + j;
j = i;
}
}
}
The methods in the outer class will only be able to access the public members of Nested, so they can only access foo() in this example - j is inaccessible. But note that methods in Nested have access to all the private members of the outer class.
I don't think there is another way of giving the scope you ask. The fact that other methods can access j in this case being a member variable is a direct consequence of the OOP concepts your are using encapsulating the members inside the holder object.
So I would continue using the member variable and don't worry about other methods being able to access it. If for some reason you must avoid other methods accessing the variable, maybe you should consider refactoring in its own type although maybe with the example given is not justified.
Hope this helps.
There is a nasty way to do that using closures. But that means you have to define your methods as anonymous functions and have them wrapped in some global method where they are defined. Consider this more an academical exercise and definitely not a production solution. For a real life solution definitely consider a separate class.
static void Main(string[] args)
{
var j = 0;
Func<int> calculateSomeValue = () =>
{
return 41;
};
Action myFoo = () =>
{
int i = calculateSomeValue() + j;
j = i;
};
}
In C this is possible with static local variables
void foo()
{
static int j;
int i = calculateSomeValue() + j;
j = i;
}
In C# this functionality was intentionally not included.
You have a couple of options, which depends on the intended lifetime of j. If you just need it for successive calls and for some reason don't want to use a loop, you can go for a recursive approach
private void foo()
{
foo(0);
}
private void foo(int j)
{
int i = calculateSomeValue() + j;
foo(j);
}
If you want more control or a longer lifetime, the objected oriented way would be to push this functionality onto a class, which can be a normal class or private and nested in your existing class.
public class ParentClass()
{
FooClass bar = new FooClass();
private class FooClass()
{
private int j = 0;
public void foo()
{
int i = calculateSomeValue() + j;
j = i;
}
private int calculateSomeValue()
{
//
}
}
private void DoStuff()
{
bar.foo();
}
}
Also I suggest re-weighing if its worth it to protect the variable in the first place.

Reference in functions C#

I know from the title you would say it's a duplicate, but...
So, I have created my class and made some objects (of class Masina) in MainWindow class constructor:
public class MainWindow
{ // example
private Masina[] _masina = new Masina[10];
_masina[0].Load(1, 'x'); // works
SomeFunction(_masina);
}
When I use this class functions in Constructor it works fine, but when I try to use some function and pass this argue like this:
public static void SomeFunction(Masina[] masina)
{
for (int i = 0; i < 10; i++)
try
{
masina[i].Load(i, 'x');
}
catch
{
}
}
then SomeFunction takes this argue as not referenced. ref don't work for me!
Can anyone help me to solve ?
Probably you want to initialize the Masina[] array in the constructor, like this:
public class MainWindow {
// Declaraion is OK, calling method _masina[0].Load(1, 'x') - is not
private Masina[] _masina = new Masina[10];
// constructor is the place you're supposed to put complex initialization to
public MainWindow() {
// You can call the method in the constructor
SomeFunction(_masina);
}
public static void SomeFunction(Masina[] masina) {
// validate arguments in the public methods
if (null == masina)
throw new ArgumentNullException("masina");
// do not use magic numbers (10), but actual parameters (masina.Length)
for (int i = 0; i < masina.Length; ++i)
masina[i].Load(i, 'x');
// hiding all exceptions - catch {} - is very bad idea
}
}

Categories

Resources