this is my c# code. There is an error I don't know, I am an intermediate programmer. check the code pls -
I have been programming and I didn't understand extension methods completely. I don't know much namespaces, and I know that my code is a bit stupid in the first class, but I put it here so you can check it out why it doesn't work. The main questions for me are -
- Why is there an error in the program?
- Why doesn't my namespace of ExtensionMethods work? I have implemented it at the top of the code also. If I make the program class non-static, and I use the namespace ExtensionMethods as normally to implement the methods, why doesn't work?
and um... here is the error details given to me by Visual Studio IDE -
System.InvalidOperationException
HResult=0x80131509
Message=Collection was modified; enumeration operation may not
execute.
Source=mscorlib
StackTrace:
at
System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource
resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at ConsoleApp1.Program.JoinWords(String s) in
and this is the code -
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using ExtensionMethods;
namespace ExtensionMethods
{
public static class TryExtensions
{
public static string JoinWords(this string s)
{
List<char> contents = new List<char>() { };
foreach (char i in s)
{
contents.Add(i);
}
foreach (char i in contents)
{
if (i == ' ')
{
contents.Remove(i);
}
}
StringBuilder somestring = new StringBuilder();
foreach (char i in contents)
{
somestring.Append(i);
}
s = somestring.ToString();
return s;
}
}
}
namespace ConsoleApp1
{
static class Program
{
public static string JoinWords(this string s)
{
List<char> contents = new List<char>() { };
foreach (char i in s)
{
contents.Add(i);
}
foreach (char i in contents)
{
if (i == ' ')
{
contents.Remove(i);
}
}
StringBuilder somestring = new StringBuilder();
foreach (char i in contents)
{
somestring.Append(i);
}
s = somestring.ToString();
return s;
}
static void Main(String[] args )
{
string sayHello = "Hello World, i really hope all spaces will be removed from this, and this sentence will be a joined one word";
sayHello = JoinWords(sayHello);
Debug.WriteLine(sayHello);
}
}
}
right so this was the code
- Why is there an error in the program?
- Why doesn't my namespace of ExtensionMethods work? I have implemented it at the top of the code also.