Calling method from within the main in c# [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have practised in C++ . It is a solution for 8-Queens that outputs all the 92 possible solutions.
C++ code example: What makes this loop so many times?
Then I have written it in C#. Here it is, But I have an error at the very end.
int[,] state = new int[8, 8];
solve_state(state, 0); // Error: an object reference is required for non-//static field,method
}
}
}
}

Try declaring the solve_state method as static.
// ↓
private static void solve_state(int[,] state, int count)
{
// method implementation here
}

It looks like you declared the solve_state as an instance (i.e. non-static) method. However, you cannot call an instance method without a reference to an instance of the parent class. Instead, make the solve_state method static, like this:
public class Program
{
public static void Main(string[] args)
{
...
int[,] state = new int[8, 8];
solve_state(state, 0);
...
}
private static void solve_state(int[,] state, int x)
{
...
}
}
Further Reading
static (C# Reference)

Related

Can’t get a specific output using a boolean [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want a specific output depending on wether the Boolean is set to true or not. I can’t seem to find the solution so I’m just asking here. I don’t what to output „true“ or „false“ but a specific text.
What I tried:
public class Program
{
bool isAlive = true;
public static void Main()
{
if (isAlive == true){
Console.WriteLine("Is True");
}
}
}
What worked:
public class Program
{
public static void Main()
{
bool isAlive = true;
if (isAlive == true){
Console.WriteLine("Is True");
}
}
}
The Error was that I tried to use the non-static variable in the static void. Thanks to everyone that helped.
you can do either
string output = bool_variable ? "true value" : "false value";
Debug.Log(output);
or
if(bool_variable == true){
Debug.Log("true value")
}else{
Debug.Log("false value")
}
Edit:
You are getting the non-static error because you are trying to access isAlive from a static method when it is not static. So you either need to create an instance of Program, make isAlive static, or remove the static keyword from Main.
Further more this does not seem to be a unity question since you are using Console.WriteLine and not implementing MonoBehaviour
You can use the following code
{boolean_variable} ? "Boolean value is true" : "Boolean value is false"

How to pass information from one void to another? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm new to coding and I have a simple problem that I cannot find the solution anywhere for.
All I would need is to pass information from one void to another.
I have tried to find a solution but many solutions go on for passing information from class to class and script to script, and that's not exactly what I need and none have worked.
The Code right now is something like this:
public static void Main(string[] args){
GetVoid.DoCheck();
}
public void GenerateInformation(){
DateTime StoredDateTime;
//Code that does something
StoredDateTime = //Date generated from the rest of the code not included
}
public void DoCheck(){
DateTime CheckedDateTime;
GenerateInformation();
CheckedDateTime = StoredDateTime;
//Rest of the code for that void
}
My end goal is for the date so simply be stored in the other DateTime but I get the error
The name 'StoredDateTime' does not exist in the current context.
As far as I know this is because it does not know what StoredDateTime is, and to fix this I would need to pass on the information from one void to the other.
But how would I do that?
void mean:
not valid or legally binding.
completely empty.
So, you cannot expect from void method to pass you result. You need to change your method signature and implement return.
public static DateTime GetDate()
{
var dateVal = DateTime.Now;
return dateVal;
}
then
public static void Main(string[] args){
var dateRetult = GetDate();
Console.WriteLine(dateResult);
}

Why the class instance value is corrupted in the multi-thread environment? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is the simple code,
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Thread thread = new Thread(new ThreadStart(()=> SimpleClass.Instance.weird.SetHello(i)));
thread.Start();
}
Console.Read();
}
}
interface IClass
{
WeirdClass weird{ get; set; }
}
class SimpleClass : IClass {
public static SimpleClass Instance = new SimpleClass();
public WeirdClass weird{ get; set; }
public SimpleClass()
{
weird= new WeirdClass();
}
}
class WeirdClass
{
public int hello;
public void SetHello(int i)
{
this.hello = i;
Console.WriteLine(this.hello);
}
}
We could see the 'hello' value in WeirdClass is not correct in multi-thread, the value is just like a static instance, but it is not.
Maybe the magic happens on SimpleClass.Instance.async, so could anyone give me some explanation about that ? Thanks
I upvoted your question since it brought me to some interesting research.
In the for loop assign the i variable to a temp ii and use ii in the thread initialization, like this:
var ii = i;
Thread thread = new Thread(
new ThreadStart(()=> SimpleClass.Instance.async.SetHello(ii)));
thread.Start();
I've tested it with different configurations and different contexts (for example, put a random Thread.Sleep between hello assignment and Console.WriteLine).
What my solution gets is this: every thread has its own unique i and gets it written on the Console a single time.
But the numbers are not written in order, since the threads don't start sequentially as you create them.
Just a side-note: as #JonSkeet recommended, don't use async as identifier, it's a reserved word. Use instead AsyncWeird, InnerClass, HelloContainer, or whatever that is not an official C# token, otherwise your code becomes less clear.
UPDATE - SOLUTION:
This:
for(int i = 0; i < 10; i++)
is equivalent to this:
int i;
for(i = 0; i < 10; i++)
That is, in both cases i is created outside the for loop, and so it is somehow shared between different cycles of the loop. If you check the link #CodeCaster provided, you'll see the same issue with the foreach loop with previous versions of C#.
If you declare the thread in a cycle with i as input, you're telling to the thread: "ok, when you start, get the i value!". In that moment, i has the proper value, but the thread asks for i only when it's effectively started, so the value has already changed because in the meantime the main thread has already begun a new cycle of the loop and has already re-assigned the i for the next iteration.
Instead, if you create a temp variable ii inside the loop, it remains in that cycle and cannot be seen outside.
This is a demonstration of the whole game: try to declare ii outside of the loop... the behavior is again the incorrect one, that you showed with the i variable.

Function won't return any value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have a problem that I think might be really easy to solve but since I'm a C# noob I can't understand what I'm doing wrong. I have two functions: addValues() and showMessage(). My problem is in addValues(). I have two MessageBox that show exactly what they're supposed to show, but in the showMessage() function the values are not being received, it always tells me that the day and dias.Count are 0. What am I doing wrong? Thank you!
On Form1:
public List<Despesas> dias = new List<Despesas>();
public struct Despesas
{
public double transportes;
public double alimentacao;
public double vestuario;
public double agua;
public double luz;
public double educacao;
}
On Class Management:
class management : Form1
{
int day=0;
public double addValues(double transportes, double alimentacao)
{
Despesas dia = new Despesas();
try
{
dia.transportes = transportes;
dia.agua = agua;
dias.Add(dia);
}
catch
{
MessageBox.Show("Error", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show("Count " + dias.Count);
day++;
MessageBox.Show("" + day);
return day;
}
public void showMessage()
{
MessageBox.Show("Day " + day);
MessageBox.Show("Count: " " + dias.Count);
for (int i = 0; i < day; i++)
{
MessageBox.Show("Agua: " + dias[i].agua + "\nTransportes: " + dias[i].transportes);
}
}
In the comments, you mention that you actually have two instances of the management class.
Changes to one instance of an object do not propagate to other instances of that object (unless it was modified on a static member, but thats a bit different).
This holds true even if you modify a base class member, as your code does. This is because instantiation of a derived class also instantiates a new base class object.
The solution is to just use one management object instance, and pass it around as needed. You do this just like any other type:
public void Foo(management myClass)
{
...
}
A few other notes:
management is not a very good name for a class, as its not very descriptive. Also, class names in C# should be PascalCase, so it should be Management
Inheritance is probably not the right relationship between management and Form1. Is management really a "type of" or "is a" Form1?

Extremely confusing for-loop behaviour [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm encountering an extremely strange behaviour with this code fragment.
Normally the for Statement doesnt enter when counted to 16 but leaves.
In my case it enters with i=16 and executes the the Zero-Case which ends in an ArrayOutOfBoundsException.
This behavior is repeated every time I call foo()
Is there any explanation for this?
void foo()
{
Thread.Sleep(2000);
try
{
for (int i = 0; i < 16; i++)
{
#region Switch
(switch on 0 to 15 and do something unrelated)
#endregion
}
}
catch (Exception ex)
{
MessageBox.Show("Exception occured: " + ex);
}
}
Why not loop upto your array length?
for (int i = 0; i < array.Length; i++)
{
//Your secret code here
}
Also make sure you're not changing the value of i inside the loop anywhere.
You'll never get the exception with this code(unless you modify i inside the loop) irrespective of array Length.

Categories

Resources