using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test
{
class Program
{
static void Main(string[] args)
{
string s1 = string.Empty;
input = Console.In.ReadLine();
RemoveDup(input);
Sort(input);
Console.Out.WriteLine(input);
Console.ReadKey();
}
static void RemoveDup(string str)
{
string finalString = string.Empty;
int len = str.Length;
for (int i = 0; i < len; i++)
{
string toAdd = str.Substring(i, 1);
for (int j = i + 1; j < len; j++)
{
if (toAdd.Equals(str.Substring(j,1)))
{
toAdd = "";
break;
}
}
finalString += toAdd;
}
str = finalString;
}
static void Sort(string str)
{
char[] toSort = str.ToCharArray();
str = string.Empty;
bool doneSearching = false;
while (!doneSearching)
{
doneSearching = true;
for (int i = 0; i < toSort.Length - 1; i++)
{
if (toSort[i] < toSort[i + 1])
{
char temp = toSort[i];
toSort[i] = toSort[i + 1];
toSort[i + 1] = temp;
doneSearching = false;
break;
}
}
}
foreach (char toAdd in toSort)
{
str += toAdd;
}
}
}
}
this program is supposed to remove the duplicates of a string and then write it sorted. However this does not work, so my guess is that my methods create a copy of the arguments being passed to it. To make the program work, I made them return string values rather than void. But what confused me is that when I'm working with something like lists, and write a simple program like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test
{
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
list.Add(0);
Console.Out.WriteLine("BEFORE CHANGE:");
foreach(int num in list)
{
Console.Out.WriteLine(num);
}
AddToList(list);
Console.Out.WriteLine("AFTER CHANGE:");
foreach (int num in list)
{
Console.Out.WriteLine(num);
}
Console.ReadKey();
}
static void AddToList(List<int> list)
{
for (int i = 1; i <= 20; i++)
{
list.Add(i);
}
}
}
}
does the list's changes stay, making me think that my theory that methods make copies of their arguments to be incorrect. Can someone please help explain to me what's going on?

New Topic/Question
Reply



MultiQuote






|