Line placement error in c# - c#

I could not find anything but the program includes five serious errors and some line placement faults. What are the faults? Thank you for your help
using System;
class Program
{
static void Main(string[] args)
{
int deger1, deger2;
deger2 = Convert.ToInt32(Console.ReadLine());
for (kivir =0; kivir <2; kivir++)
{
if (deger1 == 56)
Console.WriteLine(Ekle(kivir, deger1));
deger2--;
else deger1 = 56;
}
}
static int Ekle(int deger1, int deger2)
{
return deger1 + deger2;
}
}

kivir is not declared as a variable.
your if statement appears to have multiple statements but is missing blocks ({...}).
deger1 is not initialized
This version can compile:
using System;
class Program
{
static void Main(string[] args)
{
int deger1 = 0, deger2;
deger2 = Convert.ToInt32(Console.ReadLine());
for (int kivir =0; kivir <2; kivir++)
{
if (deger1 == 56)
{
Console.WriteLine(Ekle(kivir, deger1));
deger2--;
}
else
{
deger1 = 56;
}
}
}
static int Ekle(int deger1, int deger2)
{
return deger1 + deger2;
}
}
However, it will close the console window before you can see the output. You need to add one more Console.ReadLine() before the end of the main method.

I found one error to,there isn't a namespace.

Related

How do I set a value in one method and then return that value to another method?

I need some help. If I understand this right, the value of "int F" gets sent to "FtoC" converted and then returned to the MenuSelect1 method.
Now I want to return or save the value "int C" has after its been converted to the MenuSelect2 method? I have tried everything I can think of, but I just get errors. (I have reset the code to original state now where MenuSelect1 and 2 är void). Whats an easy way to solve this? Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class SecondClass {
public static int FtoC(int fahrenheit)
{
int C = ((fahrenheit - 32) * 5) / 9;
return C;
}
public static void MenuSelect1()
{
while (true)
{
int F = 0;
Console.Write("\nType how many degrees Fahrenheit you want: ");
try
{
F = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("ERROR!");
Console.ForegroundColor = ConsoleColor.White;
}
int C = SecondClass.FtoC(F);
if (C < 80 || C > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(C + "°C is perfect. Start the sauna and enjoy!");
break;
}
}
Console.ReadKey();
}
public static void MenuSelect2()
{
Console.WriteLine("Starting Sauna. Wait for it to reach desired temperature...");
Console.Write("Temperature: {0}");
Console.ReadKey();
}
}
You could also save the value of C as a property / field in your class. Here is an example of saving it as a field called _celcius:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class SecondClass {
private static int _celcius = 0; // <--- Your field
public static int FtoC(int fahrenheit)
{
int C = ((fahrenheit - 32) * 5) / 9;
return C;
}
public static void MenuSelect1()
{
while (true)
{
int F = 0;
Console.Write("\nType how many degrees Fahrenheit you want: ");
try
{
F = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("ERROR!");
Console.ForegroundColor = ConsoleColor.White;
}
_celcius = SecondClass.FtoC(F); // <--- Assign field here
if (_celcius < 80 || _celcius > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(_celcius + "°C is perfect. Start the sauna and enjoy!");
break;
}
}
Console.ReadKey();
}
public static void MenuSelect2()
{
Console.WriteLine("Starting Sauna. Wait for it to reach desired temperature...");
Console.Write("Temperature: {0}", _celcius); // <--- Use your field here
Console.ReadKey();
}
}```
You either call the MenuSelect2() directly from the MenuSelect1()
public static void MenuSelect1()
{
while (true)
{
int F = 0;
Console.Write("\nType how many degrees Fahrenheit you want: ");
try
{
F = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("ERROR!");
Console.ForegroundColor = ConsoleColor.White;
}
int C = SecondClass.FtoC(F);
if (C < 80 || C > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(C + "°C is perfect. Start the sauna and enjoy!");
// here
MenuSelect2(C);
break;
}
}
Console.ReadKey();
}
public static void MenuSelect2(int C)
{
Console.WriteLine("Starting Sauna. Wait for it to reach desired temperature...");
Console.Write($"Temperature: {C}"); // <- notice the $ for interpolated strings.
}
Or return the value from the MainSelect1() to the caller which calls the MainSelect2() method.
public static void Main()
{
// get the temperature
int C = MenuSelect1();
// pass it to the other method.
MenuSelect2(C);
Console.ReadKey();
}
public static int MenuSelect1() // <- change the signature (return int)
{
while (true)
{
int F = 0;
Console.Write("\nType how many degrees Fahrenheit you want: ");
try
{
F = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("ERROR!");
Console.ForegroundColor = ConsoleColor.White;
}
int C = SecondClass.FtoC(F);
if (C < 80 || C > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(C + "°C is perfect. Start the sauna and enjoy!");
return C; // return the value to the caller.
}
}
}
public static void MenuSelect2(int C)
{
Console.WriteLine("Starting Sauna. Wait for it to reach desired temperature...");
Console.Write($"Temperature: {C}"); // <- notice the $ for interpolated strings.
}
I rather use the second suggestion, because this way the MenuSelect1() isn't tightcoupled to MenuSelect2() and can be reused for other purposes.
The problem at this point is that the variable C is instantiated and stored inside the method MenuSelect1(), what you should do is create a class variable like int fahrenheitValue and then inside the menuSelect1 method use this.fahrenheitValue = C so the value is stored inside the class variable and then you can access it from everywhere
All the variables that are defined in MenuSelect1() will NOT be visible as soon as the method ends.
You can define a static property in your "SecondClass"
private static int degreesCelsius;
Then you can set this property in
if (C < 80 || C > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(C + "°C is perfect. Start the sauna and enjoy!");
degreesCelsius = C;
break;
}
In your MenuSelect2() method you can use it.
Console.Write("Temperature: {0}", degreesCelsius);

How to determine input when the can have a variable?

I'm working on this commandline based dice. And I want it to be able to output statistics and reset those internal statistics. Currently I have the following classes: Dice and DiceInterface.
I want the user to be able to use the following format for input: "'Throw' to throw the dice, alternate use 'Throw(x)', 'Stat(side)' to see how many times (side) has been thrown, or 'Reset' to reset thrown statistics"
I need a way to determine if the user has typed Throw, Throw(x), Stat(side) or Reset. Throw and Reset are obvious to me but I find it quite difficult to imagine a way to do Throw(x) and Stat(side). Does anyone have any tips or a solution?
Thanks in advance!
using System;
using System.Collections.Generic;
using System.Text;
namespace Oefening_2
{
class DiceInterface
{
static void Main()
{
StartProgram();
}
static void StartProgram()
{
Console.WriteLine("Hello, how many sides would you like the dice to have?");
var input = Console.ReadLine();
if (Int32.TryParse(input, out int number))
{
int desiredSides = number;
Dice NewDice = new Dice(desiredSides);
Console.WriteLine("What would you like to do? ");
Console.WriteLine("Type: 'Throw' to throw the dice, alternate use 'Throw(x)', 'Stat(side)' to see how many times (side) has been thrown, or 'Reset' to reset thrown statistics");
MainIO(NewDice);
}
else
{
Console.WriteLine("That is not an integer! The program will restart now...");
StartProgram();
}
}
static void MainIO(Dice CurrentDice)
{
Console.Write("Input: ");
string input = Console.ReadLine();
//Throw
if (input == "Throw")
{
Console.WriteLine(CurrentDice.Throw());
MainIO(CurrentDice);
}
//Throw(x)
else if(input == "")
//Thrown(side)
//Reset
else if (input == "Reset")
{
CurrentDice.ResetStatistics();
MainIO(CurrentDice);
}
}
}
}
using System;
namespace Oefening_2
{
class Dice
{
public int Sides { get; set; }
private readonly Random _rnd = new Random();
public int[] Thrown;
public Dice(int sides)
{
Sides = sides;
Thrown = new int[sides--];
}
public Dice():this(6)
{
}
public int Throw()
{
int thrownNumber = _rnd.Next(1, Sides);
Thrown[thrownNumber]++;
return thrownNumber;
}
public int NrOfTimesThrown(int side)
{
int result;
result = Thrown[side];
return result;
}
public void ResetStatistics()
{
for(int i = 0 ; i < Sides; i++)
{
Thrown[i] = 0;
}
}
}
}
This can be fairly simply done with StartsWith to check if a string starts with some prefix, and use .Remove to get anything after this prefix:
if(input.StartsWith("Stat"){
var parameterString = input.Remove(0, "Stat".Length);
if(int.TryParse(parameterString , out var side){
...
}
}
If I correctly understood your problem, it could be solved with an approach like this:
Console.WriteLine("Enter a value");
var s = Console.ReadLine();
if(s.Contains('('))
{
int pFrom = s.IndexOf("(");
int pTo = s.LastIndexOf(")");
var myChoice = s.Substring(0, pFrom);
var myValue = s.Substring(pFrom + 1, pTo - pFrom);
Console.WriteLine($"You choosed : {myChoice}");
Console.WriteLine($"With a value of: {myValue}");
}
This is just a brief example of how to "understand" if there is a value and then recover it.
I hope this could help you somehow.

methods program not working of guessing a number

I'm having issues creating a program that is a number guessing program. I think I have the written part right but possibly not the order of it? I have to use multiple methods such as a method for number generator of the number that is supposed to be guessed, a method for collecting the guess input, and method for checking the guess to see if it's right. I've literally have tried just about everything for days but all I get is rather a repeat of, "Enter the number: " even if its right, although it's supposed to repeat if it's too high or low. Or sometimes the console won't print anything. what is wrong? Here is the code:
using System;
namespace GuessTheNumber
{
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
return random.Next(1, 21);
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if(guess > secretNumber)
{
return "Too high!";
}
else if (guess < secretNumber)
{
return "Too low!";
}
else
{
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
while (InputGetter() != secretNumber)
{
InputGetter();
GuessChecker(InputGetter(), secretNumber);
}
if (GuessChecker(InputGetter(), secretNumber) == ("Correct!"))
{
Console.WriteLine("Would you like to play again?");
String input = Console.ReadLine();
if (GuessChecker(InputGetter(), secretNumber) == ("Yes"))
{
secretNumber = RandomNumberGenerator();
}
else if (GuessChecker(InputGetter(), secretNumber) == ("No"))
{
break;
}
}
}
}
}
}
You are invoking InputGetter() multiple times and your logic is incorrect.
It has nothing to do with Random instance being used.
I have quickly modified your code and it should work now as follows:
New number is generated, if you enter low/high message is displayed, if you enter correct number you are presented with the Would you like to try again message.
EDIT: I did not want to change original code much,In general Comparing strings is bad, you should not use it. Creating enum like and comparing would be much better
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
var generatedNumber = random.Next(1, 21);
Console.WriteLine($"New Number generated! {generatedNumber}");
return generatedNumber;
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if (guess > secretNumber)
{
Console.WriteLine("Too High");
return "Too high!";
}
else if (guess < secretNumber)
{
Console.WriteLine("Too low!");
return "Too low!";
}
else
{
Console.WriteLine("Correct");
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
int enteredNumber = 0;
do
{
enteredNumber = InputGetter();
} while (GuessChecker(enteredNumber, secretNumber)!="Correct");
Console.WriteLine("Would you like to play again?[Yes/No]");
String input = Console.ReadLine();
if (input=="Yes")
{
secretNumber = RandomNumberGenerator();
}
else
{
break;
}
}
}
}

C# Console.WriteLine not printing in one line

Now if you run this it does not output each Console.WriteLine in one line, why?
I know console.writeline goes to next line when done but the problem is it jumps to next line while printing when it print the exception var it is not in the same line as the rest of the writeline
The error occurs inside the Display() function at the number 6 variable (exception) it is not in the same line as the rest of the writeline, why?
And also there are no line breaks where the error ocurs.
Ans can be any number you like.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace EquationSolver
{
class Program
{
public static string exception = "No Solution Found yet";
public static int go = 40;
public static Decimal x = 0, formul = 0;
public static Decimal pref = -100000, next = 100000,ans;
public static Decimal stepval = next / 10;
public static Decimal prefrem = 1234567890123.1234567890m, nextrem = 1234567890123.1234567890m;
public static Decimal nextremfirst = 0;
public static void Answer()
{
Console.WriteLine("Enter ans");
ans = (Convert.ToDecimal(Console.ReadLine()));
}
public static void Main(string[] args)
{
//Console.WriteLine("Enter ans");
//Answer(Convert.ToDecimal(Console.ReadLine()));
Answer();
//Console.Clear();
while (true)
{
for (var i = 0; i <= go; i++)
{
for (x = pref; x <= next; x += stepval)
{
formul = x;
if (formul < ans)
prefrem = x;
else if (formul > ans)
{
if (nextremfirst == 0)
{
nextrem = x;
nextremfirst += 2;
}
}
else if (formul == ans)
{
AnsFound();
break;
}
else
{
Error();
}
Display();
}
if (formul == ans)
{
AnsFound();
break;
}
if (prefrem != 1234567890123.1234567890m)
pref = prefrem;
if (nextrem != 1234567890123.1234567890m)
next = nextrem;
nextremfirst = 0;
stepval /= 10;
if (formul != ans)
NoAnsyet();
//Console.WriteLine();
}
Finnish();
}
}
public static void Display()
{
//Console.ReadKey();
//Console.WriteLine("Formul: {0} x: {1} Ans: {2} Status: {3}", //formul, x, ans, exception);
//Here is the error:
Console.WriteLine("Pref:{0} Next:{1} Step:{2} Formul:{3} x:{4} Ans:{5} Status:{6}",pref,next,stepval,formul,x,ans,exception);
}
public static void Finnish()
{
if (formul != ans)
Error();
exception = "\ncomplete";
Console.WriteLine(exception);
pref = -100000;
next = 100000;
stepval = next /= 10;
Console.ReadKey();
Console.Clear();
//Console.WriteLine("Enter ans:");
//Answer(Convert.ToDecimal(Console.ReadLine()));
Answer();
}
public static void AnsFound()
{
exception = "\nSolution Found!";
//Console.WriteLine("x: {0} Ans: {1} Status: {2}", x, ans, exception);
//Console.WriteLine("Pref:{0} Next: {1} Stepval: {2} Formul:{3} x:{4} Ans:{5} Status:{}", pref, next, stepval, formul, x, ans, exception);
}
public static void NoAnsyet()
{
exception = "\nNo Solution yet...";
//Console.WriteLine(exception);
}
public static void Error()
{
exception = "\nNo Solution error!!";
Console.WriteLine(exception);
}
}
}
Because you set exception = "\ncomplete"; at different places. The \n at the beginning is a new line character.
Remove the \n
exception = "complete";
Same problem with other texts like "\nSolution Found!".
Using string interpolation makes string formatting more readable:
Replace
Console.WriteLine("Pref:{0} Next:{1} Step:{2} Formul:{3} x:{4} Ans:{5} Status:{6}",
pref, next, stepval, formul, x, ans, exception);
by
Console.WriteLine(
$"Pref:{pref} Next:{next} Step:{stepval} Formul:{formul} x:{x} Ans:{ans} Status:{exception}");
WriteLine writes in a New Line. You should try
Console.Write()
If you want to print right after your previous print.
The value to your variable exception is the reason why the console is printing on a different basically if you put a special character \n means new line hence all the methods you are calling have this special character.
Solution remove special characters and use the Console.WriteLine or Console.Write methods
As per the code provided you have not called the method i made some changes to the code
Edited code
and try to run the code status :No solution found yet
Thanks

Error 1 Cannot implicitly convert type 'int**' to 'int*'. An explicit conversion exists (are you missing a cast?)

I'm learning C and C# and this question is for C#. I looking at pointers at msdn and this code is not compiling, it gives the error:Error 1 Cannot implicitly convert type int** to int*. An explicit conversion exists (are you missing a cast?). What am I missing here?
Here is the code:
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix; **The error is on this line**
}
EDIT:
Here is the program in its entirety:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Diagnostics;
using System.Windows.Forms;
using practice;
class Program
{
public delegate bool ThisIsTheDelegate(int number);
public delegate bool ThisIsAnotherDelegate(int number);
private static string address;
public static String Address
{
get
{
return address;
}
set
{
address = value;
}
}
static void Main()
{
int[] someArray = new int[] { 1, 2, 3, 5, 6, 7, 8, 9, 0 };
foreach (int number in someArray)
{
Console.WriteLine(number);
}
int integer = 98;
string someString = "edited";
string[] someStr = { "edited" };
String[] anotherStringSomestr = new String[] { "edited" };
var readWithLinq = from far in anotherStringSomestr
select far;
foreach (var some in readWithLinq)
{
Console.WriteLine(some);
}
Program newPro = new Program();
bool isEven1 = newPro.isEven(99);
Console.WriteLine(isEven1);
ThisIsTheDelegate newDelegate = newPro.isEven;
Console.WriteLine(newDelegate(98));
int[] numbers = { 1, 2, 3, 5, 6, 7, 8, 9 };
List<int> evenNumbers = FilterArray(numbers, newDelegate);
foreach(int integer1 in evenNumbers)
{
Console.WriteLine(integer1);
}
List<int> oddNumbers = FilterArray(numbers, isOdd);
foreach (int integer1 in oddNumbers)
{
Console.WriteLine(integer1);
}
ThisIsAnotherDelegate anotherDelegate;
anotherDelegate = number => (number % 2 == 0);
Console.WriteLine("{0} is a even number", anotherDelegate(4));
for (int i = 0; i < someString.Length; i++)
{
Console.WriteLine(someString);
}
for (int i = 0; i < someStr.Length; i++)
{
Console.WriteLine(someStr[i]);
}
Console.WriteLine(integer);
SimpleStruct structss = new SimpleStruct();
structss.DisplayX();
M.x = 1;
structss.x = 98;
Console.WriteLine(M.x);
Console.WriteLine(structss.x);
M.structtaker(ref structss);
M.classtaker();
Console.WriteLine(structss.x);
Console.WriteLine(M.x);
M.x = 1;
structss.x = 98;
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
}
int selection = 98;
while (selection != 0)
{
mainMenu();
Console.Write("Enter choice: ");
selection = Convert.ToInt32(Console.ReadLine());
switch (selection)
{
case 0:
break;
case 1:
openSomething();
break;
case 2:
calculator();
break;
case 3:
coolestProgramEverALive();
break;
case 4:
make_to_do_list();
break;
case 5:
add_to_do_list();
break;
case 6:
readToDoList();
break;
case 7:
linq_and_arrays();
break;
case 8:
calendar();
break;
case 9:
linq_and_collections();
break;
default:
Console.WriteLine("Unkown selection. Try again");
break;
}
}
}
private static bool isOdd(int number)
{
return (number % 2 == 1);
}
private static List<int> FilterArray(int[] numbers, ThisIsTheDelegate newDelegate)
{
List<int> result = new List<int>();
foreach (int item in numbers)
{
if (newDelegate(item))
result.Add(item);
}
return result;
}
private static void linq_and_collections()
{
List<string> names = new List<string>();
names.Add("Billy");
names.Add("Steve");
names.Add("Casandra");
names.Insert(0, "Johanna");
names.Add("Sonny");
names.Add("Suzanne");
names.Insert(2, "Sid");
var queryLinqUpper = from name in names
where (name.StartsWith("S") || name.StartsWith("B") || name.StartsWith("J"))
let namesToUpper = name.ToUpper()
orderby namesToUpper
select namesToUpper;
foreach (var linqToUpper in queryLinqUpper)
{
Console.Write(linqToUpper + " ");
}
Console.WriteLine();
M.WriteTextToConsole("Hello, world. Programming in C# is fun");
char c = 'A';
int count = 14;
String str = new String(c, count);
str.WriteTextToConsole();
M.WriteTextToConsole(str);
}
private static void calendar()
{
Application.Run(new Form1());
}
private static void readToDoList()
{
var files = from file in Directory.GetFiles(#"C:\data", "*.txt")
select file;
int number = 1;
foreach (var file in files)
{
Console.WriteLine(number + ". " + file);
number++;
}
Console.Write("What todolist do you want to read? Give me the name:");
try
{
string name = Console.ReadLine();
Address = Path.Combine(#"C:\data", name + ".txt");
TextReader inFile = new StreamReader(Address);
while (inFile.Peek() != -1)
{
string line = inFile.ReadLine();
Console.WriteLine(line);
}
inFile.Close();
}
catch (Exception ex)
{
MessageBox.Show("Exception thrown!", "Error");
Console.WriteLine(ex.ToString());
}
}
private static void linq_and_arrays()
{
int numberOfElements;
Console.WriteLine("Start by setting the int[] array.");
Console.Write("How many elements are there in your array?");
numberOfElements = Convert.ToInt32(Console.ReadLine());
int[] array = new int[numberOfElements];
for (int i = 0, j = numberOfElements; i < numberOfElements; i++, j--)
{
Console.Write("Integers left to add {0}. Enter an integer:", j);
array[i] = Convert.ToInt32(Console.ReadLine());
}
var arrayquery = from value in array
select value;
foreach (var val in arrayquery)
{
Console.WriteLine("Value from array:{0}", val);
}
}
private static void add_to_do_list()
{
Console.WriteLine("Which todolist do you want to modify?");
listToDoLists();
Console.Write("Enter name of todolist: ");
string name = Console.ReadLine();
Address = Path.Combine(#"C:\data", name + ".txt");
String tempString;
StreamWriter stream;
stream = File.AppendText(Address);
Console.Write("Enter your new ToDo: ");
tempString = Console.ReadLine();
stream.WriteLine(tempString);
stream.Close();
TextReader inFile;
inFile = new StreamReader(Address);
while (inFile.Peek() != -1)
{
string line = inFile.ReadLine();
Console.WriteLine(line);
}
inFile.Close();
}
private static void listToDoLists()
{
int filenumber = 1;
string[] filepaths = Directory.GetFiles("C:\\data\\", "*.txt");
foreach (string file in filepaths)
{
Console.WriteLine(filenumber + ". " + file);
filenumber++;
}
}
private static void make_to_do_list()
{
string path, name;
string yesOrNo;
Console.Write("Enter name of todolist: ");
name = Console.ReadLine();
path = Path.Combine(#"C:\data", name + ".txt");
TextWriter outFile = new StreamWriter(path);
labelOne: // else clause : unknown answer
Console.WriteLine("Do you want to add something to todolist.Y/N?");
yesOrNo = Console.ReadLine();
if (yesOrNo.ToLower() == "y")
{
string line;
int lines;
Console.Write("How many lines?");
lines = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < lines; i++)
{
Console.Write("Enter a line of text: ");
line = Console.ReadLine();
outFile.WriteLine(line);
}
outFile.Close();
}
else if (yesOrNo.ToLower() == "n")
{
Console.WriteLine("You can close the application now.");
}
else
{
Console.WriteLine("Unknown answer. Try again");
goto labelOne;
}
}
private static void coolestProgramEverALive()
{
System.Diagnostics.Process.Start(#"C:\Users\KristjanBEstur\Documents\Visual Studio 2012\Projects\The_coolest_program_ever_alive\The_coolest_program_ever_alive\obj\Debug\The_coolest_program_ever_alive.exe");
}
private static void calculator()
{
System.Diagnostics.Process.Start("calc");
}
private static void openSomething()
{
System.Diagnostics.Process.Start("notepad");
}
private static void mainMenu()
{
Console.WriteLine("Main Menu");
Console.WriteLine("0. Quit");
Console.WriteLine("1. OpenSomething");
Console.WriteLine("2. Calculator");
Console.WriteLine("3. coolestProgramEverAlive");
Console.WriteLine("4. Make todolist");
Console.WriteLine("5. Add to todolist");
Console.WriteLine("6. Read to do list");
Console.WriteLine("7. Linq and arrays");
Console.WriteLine("8. Calendar");
Console.WriteLine("9. Linq and collections");
}
public bool isEven(int number)
{
return (number % 2 == 0);
}
}
static class M
{
public static int x;
public static void WriteTextToConsole(this string text)
{
Console.WriteLine(text);
}
public static void structtaker(ref SimpleStruct s)
{
s.x = 5;
}
public static void classtaker()
{
M.x = 5;
}
}
class Test
{
static int value = 20;
unsafe static void F(out int* pi1, ref int* pi2) {
int i = 10;
pi1 = &i;
fixed (int* pj = &value) {
// ...
pi2 = pj;
}
}
}
struct SimpleStruct
{
public int x;
private int xval;
public int X
{
get
{
return xval;
}
set
{
if (value < 100)
xval = value;
}
}
public void DisplayX()
{
Console.WriteLine("The stored value is: {0}", X);
}
}
I wished I could replicate this it seems like a rather interesting issue. Here is the section of the standard that I believe applies to this (sorry about the formatting):
18.3 Fixed and moveable variables The address-of operator (§18.5.4) and the fixed statement (§18.6) divide variables into two categories:
Fixed variables and moveable variables. Fixed variables reside in
storage locations that are unaffected by operation of the garbage
collector. (Examples of fixed variables include local variables, value
parameters, and variables created by dereferencing pointers.) On the
other hand, moveable variables reside in storage locations that are
subject to relocation or disposal by the garbage collector. (Examples
of moveable variables include fields in objects and elements of
arrays.) The & operator (§18.5.4) permits the address of a fixed
variable to be obtained without restrictions. However, because a
moveable variable is subject to relocation or disposal by the garbage
collector, the address of a moveable variable can only be obtained
using a fixed statement (§18.6), and that address remains valid only
for the duration of that fixed statement. In precise terms, a fixed
variable is one of the following: • A variable resulting from a
simple-name (§7.6.2) that refers to a local variable or a value
parameter, unless the variable is captured by an anonymous function.
• A variable resulting from a member-access (§7.6.4) of the form V.I,
where V is a fixed variable of a struct-type. • A variable resulting
from a pointer-indirection-expression (§18.5.1) of the form *P, a
pointer-member-access (§18.5.2) of the form P->I, or a
pointer-element-access (§18.5.3) of the form P[E]. All other variables
are classified as moveable variables. Note that a static field is
classified as a moveable variable. Also note that a ref or out
parameter is classified as a moveable variable, even if the argument
given for the parameter is a fixed variable. Finally, note that a
variable produced by dereferencing a pointer is always classified as a
fixed variable.
I spend some time trying to create a similar error but wasn't about to. The only way I was able to recreate the issue was with the following code:
void test() {
int ix = 10;
unsafe {
int* px1 = &ix;
int* px2 = &px1; // **The error is on this line**
}
}
Of course this code cannot be fixed by moving the ix declaration into the safe scope. Perhaps you could try replicating the original problem in a very small bit of code (like above) and verify that both the problem and the fix replicate. Perhaps VS became confused. I have had problems that made no sense and went away by exiting VS and restarting (not often but a few times).
I moved the i declaration down inside the unsafe block and it fixed it, I don't know why?
Here is the code:
unsafe
{
int ix = 10;
int* px1;
int* px2 = &ix;
}
I've moved the expression "int i = 10;" out of the unsafe block and now it compiles. I've also put the code in question in a new project of another instance of vs2012pro. And that also compiles. So now I'm unable to replicate the error.
Here is the code:
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
Test.F(out px1, ref px2);
Console.WriteLine("*px1 = {0}, *px2 = {1}",
*px1, *px2); // undefined behavior
}
Here is the other project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace saxerium
{
class Program
{
static void Main(string[] args)
{
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
Test.F(out px1, ref px2);
Console.WriteLine("*px1 = {0}, *px2 = {1}",
*px1, *px2); // undefined behavior
}
}
}
class Test
{
static int value = 20;
public unsafe static void F(out int* pi1, ref int* pi2)
{
int i = 10;
pi1 = &i;
fixed (int* pj = &value)
{
// ...
pi2 = pj;
}
}
}
}

Categories