Pass variables between methods - c#

I have 2 methods in my program.
1. Start Exam
2. Mark Exam
as you see,
in first method i calculated how many questions are correct or wrong.
in second, i want to show the result.
PROBLEM:
How can i pass the correctlyAnswers and wrongAnswers and LIST between methods?
this is what i have:
static void Main(string[] args)
{
int menuChoice = 99;
Question[] questions = new Question[30];
do
{
Console.Clear();
DisplayMenu();
menuChoice = InputOutput_v1.GetValidInt("Option");
switch (menuChoice)
{
case 1:
InputOutput_v1.DisplayTitle("Start Exam");
CreateQuestion(questions);
break;
case 2:
InputOutput_v1.DisplayTitle("Mark Exam");
DisplayAllQuestions(questions);
break;
}
} while (menuChoice != '0') ;
}
public static void StartExam(Question[] questions)
{
char[] studentAnswers = new char[30];
int[] wrongAnswers = new int[30];
int correctlyAnswered = 0;
int falselyAnswered = 0;
string list = "";
Console.Clear();
Console.WriteLine("== DO NOT CHEAT! ==\n");
Console.WriteLine("----------------");
for (int i = 0; i < studentAnswers.Length; i++)
{
Console.WriteLine("\nQuestion {0}", i + 1);
Console.WriteLine("------------");
questions[i].DisplayQuestion();
studentAnswers[i] = InputOutput_v1.GetValidChar("Your Answer (A, B, C, D)");
if (studentAnswers[i] == questions[i].correctAnswer)
{
correctlyAnswered = correctlyAnswered + 1;
}
else
{
falselyAnswered = falselyAnswered + 1;
wrongAnswers[i] = i + 1;
list += i + 1 + ", ";
}
}
}
public static void MarkExam(Question[] questions)
{
if (correctlyAnswered >= 15)
{
Console.WriteLine("Passed with {0} correct answers", correctlyAnswered);
}
else
{
Console.WriteLine("Failed with {0} incorrect answers. Incorrect answers are: {1} ", falselyAnswered, list.Remove(list.Length - 2));
}
Console.ReadLine();
}

Well, why can't you call your MarkExam() method passing those variables like
public static void StartExam(Question[] questions)
{
char[] studentAnswers = new char[30];
int[] wrongAnswers = new int[30];
int correctlyAnswered = 0;
int falselyAnswered = 0;
string list = "";
........
MarkExam(questions, wrongAnswers, correctlyAnswered);
In which case you will have to change your method signature accordingly

Make the correctlyAnswers, wrongAnswers, and LIST defined as global variables outside your methods, e.g.
private int correctlyAnswered;
private int falselyAnswered;
private Question[] questions;

First, why are you using an array instead of a list? And inside this class your methods don't really need to be static.
Second, create private variables to the class and they can be used in all methods.
public class ExamClass
{
private List<Question> questions = new List<Question>();
private List<Question> incorrect = new List<Question>();
private List<Question> correct = new List<Question>();
...
}

Related

How do you return 2 variables in C#/csharp? [duplicate]

This question already has answers here:
Return multiple values to a method caller
(28 answers)
Returning anonymous type in C#
(16 answers)
Closed 3 years ago.
Refer to method WutHap (sorry, I didn't write comments), I need to return both int agg and int sub to get the method NumGen would have on int agg and sub in Main. I know you can use arrays and tuples, but I'm having trouble doing it. If you need any more context, please ask what needs to be clarified. I'm stupid, so saying that it needs more context will probably not lead to actual clarification. Yes, I know the code is abysmal but that isn't the focus.
class Program
{
static void Main(string[] args)
{
int agg = 50;
int sub = 50;
for (int i = 0; i < 100; i++)
{
WutHap(agg, sub);
}
int pop = sub + agg;
Console.WriteLine("Total aggs = " + agg);
Console.WriteLine("Total subs = " + sub);
Console.WriteLine("Total population = " + pop);
Console.ReadKey();
}
static string NumGen()
{
string[] pengs = new string[2]{"agg", "sub"};
Random numGen = new Random();
int mepi = numGen.Next(1, 2);
int mepi2 = numGen.Next(1, 2);
string pemi = pengs[mepi];
string pemi2 = pengs[mepi2];
string whoMet = pemi + ", " + pemi2;
return whoMet;
}
static int WutHap(int agg, int sub)
{
NumGen();
switch (NumGen())
{
case ("agg, agg"):
--agg;
--agg;
break;
case ("agg, sub"):
++agg;
++agg;
++agg;
--sub;
break;
case ("sub, agg"):
--sub;
++agg;
++agg;
++agg;
break;
case ("sub, sub"):
++sub;
++sub;
break;
}
}
}
You can use C# 7 syntax to return multiple values from method:
static void Main(string[] args)
{
var (a, b) = Foo();
}
private static (int, int) Foo()
{
return (1, 2);
}
UPDATE:
Using Tuple<int, int>:
static void Main(string[] args)
{
var (a, b) = GetMultipleValue();
Tuple<int, int> tuple = GetMultipleValue();
}
public static Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1, 2);
}

Foreach won't return elements of char list

So im making this hangman game, as Im trying to learn C# but now im stuck with System.Collection.Generic.List'1[System.Char]. What im trying to do is to save wrong answers into List nepravilne, look into functions izpis and igra
class Program
{
static private int _sccore;
static void Main(string[] args)
{
string beseda;
int dolzina;
bool play=true;
char input;
do
{
beseda = izberi_besedo();
dolzina = beseda.Length;
igra(beseda, dolzina);
Console.WriteLine("Vnesite Y za nadaljevanje ali N za zakljucitev igre.");
input = char.Parse(Console.ReadLine());
if (input.Equals('y'))
{
play = true;
Console.WriteLine("play {0}",play);
}
if (input.Equals('n'))
{
play = false;
Console.WriteLine("play {0}", play);
}
} while (play == true);
}
static private string izberi_besedo() {
string[] besede = { "voda", "ladija", "letalo", "motor", "klavir", "harmonika", "saksofon", "oklep", "penkalo", "tiskalnik", "miza", "copat", "krogla", "klobuk", "gumb", "harfa", "kontrabas", "mandarina", "les", "knjiga", "vlak", "vijak", "struna", "kozarec" };
Random rnd = new Random();
int stevilka = rnd.Next(0, 23);
string beseda = besede[stevilka];
return beseda;
}
static private void igra (string beseda, int dolzina){
int i, poizkusi = 0;
int pravilne = 0;
bool endloop = false;
char crka;
List<char> nepravilne = new List<char>();//declaring char list for wrong words
string[] odkrite = new string[dolzina];
for(i=0; i<dolzina; i++) { odkrite[i] = "_"; }
do {
izpis(odkrite,nepravilne); //izpis - function which returns just text, we are inputing list nepravilne, which are wrong answers
vpis(out crka);
if (!(beseda.Contains(crka)))//if word doesen't contain letter
{
poizkusi++;
_sccore--;
nepravilne.Add(crka);//add that letter to list
}
for (i = 0; i<dolzina; i++)
{
if (crka.Equals(beseda[i]))
{
odkrite[i] = Convert.ToString(crka);
pravilne++;
_sccore++;
}
}
Console.Clear();
if (pravilne >= dolzina || poizkusi >= 4)endloop = true;
} while (endloop==false);
}
static private void vpis(out char crka)
{
string vpis;
bool stevilka=false, status;
Console.WriteLine("\nVnesite crko za ugibanje besede");
vpis = Console.ReadLine();
stevilka = IsNumeric(vpis);
if (vpis.Length == 1 && stevilka==false)
{
crka = Convert.ToChar(vpis);
}
else
{
do
{
status = false;
if (vpis.Length!=1) Console.WriteLine("Vnesli ste prevec crk, poizkusite ponovno");
if(stevilka==true) Console.WriteLine("Vnesli ste stevilko, poizkusite ponovno");
vpis = Console.ReadLine();
stevilka = IsNumeric(vpis);
if (vpis.Length == 1 && stevilka == false)
{
status = true;
}
} while (status==false);
crka = Convert.ToChar(vpis);
}
}
private static bool IsNumeric(string vpis)
{
int number;
return int.TryParse(vpis, out number);
}
private static void izpis(string[] odkrite, List<char> nepravilne)
{
Console.Write("Rezultat {0} | ", _sccore);
foreach (char element in nepravilne)//write out char elements which contain letter
{
Console.Write("{0} ", nepravilne);
}
Console.WriteLine();
foreach (string element in odkrite)
{
Console.Write("{0} ", element);
}
}
}
}
I think you have a typo in the following code, i.e I think you are intending to print the variable element in the loop and not nepravilne:
foreach (char element in nepravilne)
{
Console.Write("{0} ", nepravilne);
}
Should be as follows instead?
foreach (char element in nepravilne)
{
Console.Write("{0} ", element);
}

Using an int in another method

Hey guys I need to use an Int called points from method ValidateAns in a Method Main. I searched around the net and people said I should do ValidateAns(points), however it does not work for me, Im not sure if I'm doing it wrong or I should use some other way to do it
static void Main(string[] args)
{
const int QuestionNumbers = 10;
char[] Answear = new char[QuestionNumbers];
Question[] MCQ = new Question[QuestionNumbers];
MCQ[0] = new Question(Slaughterhouse);
MCQ[1] = new Question(Frankenstein);
MCQ[2] = new Question(Things);
MCQ[3] = new Question(Jane);
MCQ[4] = new Question(Kill);
MCQ[5] = new Question(Beloved);
MCQ[6] = new Question(Gatsby);
MCQ[7] = new Question(Catcher);
MCQ[8] = new Question(Pride);
MCQ[9] = new Question(Nineteen);
for (int i = 0; i < QuestionNumbers; i++)
{
Console.WriteLine("Question {0}", i + 1);
Answear[i] = MCQ[i]();
ValidateAns(i + 1, Answear[i]);
Console.WriteLine();
Console.ReadKey();
}
}
static void ValidateAns(int Nbr, char Ans)
{
int points= 0;
switch (Nbr)
{
case 1:
if (Ans == 'b' || Ans == 'B')
{
Console.WriteLine("Good Answear");
points++;
break;
}
else
{
Console.WriteLine("Wrong Answer - The right answer was (B)");
break;
}
}
}
I restructured the members you gave us.
Think about naming convention, if you're going to validate something you would need to return a Boolean or bool to state whether the answer was give is valid or not. see IsValidAnswer(). When writing members that return a bool think of using a linking verb. Is, Has, Will.
when you compare the type char you can use char.ToUpperInvariant(char val), so you dont have to compare your answer to too different cases of the same character.
i hope this helps, check out the comments in the code. There is a nugget in there that you will love as a developer. :) have a good day
private static void Main(string[] args)
{
const int QuestionNumbers = 10;
var Answer = new char[QuestionNumbers];
Question[] MCQ = new Question[QuestionNumbers];
MCQ[0] = new Question(Slaughterhouse);
MCQ[1] = new Question(Frankenstein);
MCQ[2] = new Question(Things);
MCQ[3] = new Question(Jane);
MCQ[4] = new Question(Kill);
MCQ[5] = new Question(Beloved);
MCQ[6] = new Question(Gatsby);
MCQ[7] = new Question(Catcher);
MCQ[8] = new Question(Pride);
MCQ[9] = new Question(Nineteen);
for (int i = 0; i < QuestionNumbers; i++)
{
Console.WriteLine("Question {0}", i + 1);
Answer[i] = MCQ[i]();
// return bool since you want to validate an answer.
var result = IsValidAnswer(i + 1, Answer[i]);
// this is an if/else conditional statment, its called a ternary expression
Console.WriteLine(result ? "Answer is valid" : "Answer is not valid");
Console.WriteLine();
Console.ReadKey();
}
}
private static bool IsValidAnswer(int Nbr, char Ans)
{
// if you really wanted to use a method.
var correctAnswer = default(char);
switch (Nbr)
{
case 1:
correctAnswer = 'b';
break;
case 2:
//..
break;
}
return char.ToUpperInvariant(Ans) == char.ToUpperInvariant(correctAnswer);
}
define your function as
static int ValidateAns(int Nbr, char Ans)
and return the points value with return points;
then call it with something like
int p=ValidateAns(i + 1, Answear[i]);

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;
}
}
}
}

Updating a list using a method?

This is a really simple question concerning a method. I'm pretty new to C# and am testing lists. How do I call the method "addTwo" so that it updates every element in the "Marks" list by two? Please note that I've already created this method (scroll down further below the main method). I just want to know how to call it in the main method.
namespace ParallelLists
{
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
//Upgrade everyone by 2 marks
...
}
public List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
}
}
You need to make your method static, since you are accessing on a non object. also you need to update your marks collection with the returned value. You dont actually need to return the List because list is mutable.
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
marks = addTwo(marks);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
Console.Read();
}
public static List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
}
if you dont want to return the list, you can do the following:
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
addTwo(marks);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
Console.Read();
}
public static void addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
}
}
Your list is already getting a reference to 'mark' why return anything when any operation you are doing will operate on that same list.
instead of:
public List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
I would do:
public void addTwo(List<decimal> mark)
{
for (int i = 0; i < mark.Count; i++)
{
temp[i] += 2m;
}
}
Then in your code call is just as
addTwo(mark);
I would rename it to AddTwo to fit normal c# conventions as well.
//Upgrade everyone by 2 marks
var plustwo = addTwo(marks);
Console.WriteLine("the mark of " + names[0] + " is : " + plustwo[0]);
Console.ReadLine();
Note, that you will also need to make AddTwo a static method:
public static List<decimal> addTwo(List<decimal> mark)

Categories