namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface HelloWorldService
{
[OperationContract]
[WebGet(UriTemplate = "")]
public string HelloWorld() //here
{
return "Hello world!";
}
}
}
I get this error:
Error 1 The modifier 'public' is not valid for this item
This is what I have in my svc.cs file
public class Service1 : HelloWorldService
{
public string HelloWorld()
{
return string.Format("Hello World!");
}
}
This is actually from a tutorial from my uni:
Unlike last week, where we created interfaces for our services first, we are simply going to create WCF service objects in this first example. This is to save on time within the tutorial. Best practice means that we should be creating interfaces for all our services, which relates to the defined service contract. First of all create a new project within Visual Studio 2008 (remember to add the System.ServiceModel and System.ServiceModel.Web references, and the using declaration for both of these namespaces), and add the following class definition:
[ServiceContract]
public class HelloWorldService
{
[OperationContract]
[WebGet(UriTemplate="")]
public string HelloWorld()
{
return "Hello world!";
}
}
You should be familiar with the basic structure of this WCF service from last week’s tutorial. The difference lies in the extra attribute we have added to the method:
[WebGet(UriTemplate=»»)]
This attribute states that the service receives HTTP GET messages (the WebGet part), and that the rest of the URL is not relevant to the service end point (this will become clearer after the later examples). To host this service, we require the following main application:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using IronPython.Hosting; using Microsoft.Scripting.Hosting; public bool CheckPythonCode(string pythonCode, string inputData, string expectedOutput) { // Создаем движок Python var engine = Python.CreateEngine(); // Создаем область выполнения Python var scope = engine.CreateScope(); // Выполняем код программы-чекера на Python engine.Execute(pythonCode, scope); // Получаем функцию проверки из области выполнения Python var checkFunction = scope.GetVariable<Func<string, string, bool>>("check"); // Вызываем функцию проверки и получаем результат var result = checkFunction(inputData, expectedOutput); return result; } namespace TestChecker { public class Rez { public string Status; // public string Error; // public int score; }; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private async void button1_Click(object sender, EventArgs e) { //string Source = textBox_Source.Text.Replace("{1}", textBox1.Text.Replace("rn", "\r\n")).Replace("{2}", textBox2.Text.Replace("rn", "\r\n")).Replace("{I}", textBox_Input.Text.Replace("rn", "\r\n")); string Source = textBox_Source.Text; //string input = textBox1.Text.Replace("rn", "\r\n"); string answer = textBox1.Text.Replace("rn", "\r\n"); string user = textBox2.Text.Replace("rn", "\r\n"); StringBuilder sb = new StringBuilder(); /* using (System.IO.StringReader reader = new System.IO.StringReader(Source)) { sb.Append(reader.ReadLine()); } Source = sb.ToString();*/ // Source = Source.Replace("rn", " "); // Source = Source.Replace("n", " \r\n"); String script = Source; CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.Core.dll"); options.ReferencedAssemblies.Add("System.Drawing.dll"); options.ReferencedAssemblies.Add("System.Data.dll"); options.ReferencedAssemblies.Add("System.Xml.dll"); var provOptions = new Dictionary<string, string> { { "CompilerVersion", "v3.5" } }; //var provOptions = new Dictionary<string, string>(); // Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(provOptions); // CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); CompilerResults result = provider.CompileAssemblyFromSource(options, script); // Check the compiler results for errors StringWriter sw = new StringWriter(); foreach (CompilerError ce in result.Errors) { if (ce.IsWarning) continue; sw.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText); } // If there were errors, raise an exception... string errorText = sw.ToString(); if (errorText.Length > 0) // throw new ApplicationException(errorText); richTextBox1.Text = errorText; else richTextBox1.Clear(); using (Microsoft.CSharp.CSharpCodeProvider foo = new Microsoft.CSharp.CSharpCodeProvider(provOptions)) { var res = foo.CompileAssemblyFromSource( new System.CodeDom.Compiler.CompilerParameters(new[] { "System.dll", "System.Core.dll", "System.Drawing.dll", "System.Data.dll", "System.Xml.dll" }) { GenerateInMemory = true }, // "public class Check { public string Execute() { if( 1 == 2) return "Accepted"; else return "Wa"; }}" // "using System; public class Check { public string Execute() { double eps = 0.000001; if( Math.Abs(17.000000 - 17.000002) <=eps) return "Accepted"; else return "Wa"; }}" //"public class Check { public string Execute() { rnrnif( 0 == 0)rnreturn "Accepted";rnelsernreturn "Wa";rnrn}}" Source ); try { var type = res.CompiledAssembly.GetType("Check"); var obj = Activator.CreateInstance(type); var rslt = type.GetMethod("Execute").Invoke(obj, new object[] { answer, user }); string[] rez = rslt as string[]; // return output as string; label2.Text = rez[0].ToString()+" "+ rez[1]+" "+ rez[2]; } catch (Exception e1) { label1.Text = DateTime.Now.ToLongTimeString() + " " + e1.InnerException; return; } } /* string Source = textBox_Source.Text.Replace("{1}", textBox1.Text.Replace("rn","\r\n")).Replace("{2}", textBox2.Text.Replace("rn", "\r\n")).Replace("{I}",textBox_Input.Text.Replace("rn", "\r\n")); StringBuilder sb = new StringBuilder(); String script = Source; CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.Core.dll"); options.ReferencedAssemblies.Add("System.Drawing.dll"); options.ReferencedAssemblies.Add("System.Data.dll"); options.CompilerOptions = "/optimize"; var provOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }; //var provOptions = new Dictionary<string, string>(); // Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); //Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(provOptions); CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); CompilerResults result = provider.CompileAssemblyFromSource(options, script); // Check the compiler results for errors StringWriter sw = new StringWriter(); foreach (CompilerError ce in result.Errors) { if (ce.IsWarning) continue; sw.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText); } // If there were errors, raise an exception... string errorText = sw.ToString(); if (errorText.Length > 0) // throw new ApplicationException(errorText); richTextBox1.Text = errorText; else richTextBox1.Clear(); try { var type = result.CompiledAssembly.GetType("Check"); var obj = Activator.CreateInstance(type); var output = type.GetMethod("Execute").Invoke(obj, new object[] { }); // return output as string; label2.Text = output.ToString(); } catch (Exception e1) { label1.Text = DateTime.Now.ToLongTimeString() + " " + e1.Message; return; } */ } private void textBox_Source_TextChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { } } } |
when i declare the function, i get the following error
«The modifier ‘public’ is not valid for this item [c# class]».
here’s my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace c__class
{
class Program
{
static void Main(string[] args)
{
string meow = "meow";
public static void sayMeow (ref string purr) { //gets an error
purr = "meow meow";
Console.WriteLine("purr");
}
sayMeow(ref meow);
Console.WriteLine(meow);
}
}
}
when i remove the public keyword it works, can someone tell me why?
![]()
Vivek Nuna
24.4k21 gold badges105 silver badges194 bronze badges
asked Oct 17, 2021 at 12:13
1
You are declaring a function inside a method. Inner functions are not allowed to have access modifiers:
«Unlike a method definition, a local function definition cannot include the member access modifier. Because all local functions are private, including an access modifier, such as the private keyword, generates compiler error CS0106, «The modifier ‘private’ is not valid for this item.»
Either remove the modifier or move the function outside the method.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions
answered Oct 17, 2021 at 12:17
![]()
Mayur EkboteMayur Ekbote
1,6501 gold badge11 silver badges14 bronze badges
As local functions are implicitly private to the method, so there is no need to explicitly declare with member access modifier.
Because Local functions are private methods of a type that are nested in another member. They can only be called from their containing member.
Official documentation is here.
answered Oct 17, 2021 at 12:18
![]()
Vivek NunaVivek Nuna
24.4k21 gold badges105 silver badges194 bronze badges
You are defining the the function inside another function (Main). Functions inside other functions cannot be public or anything like that.
What you want to do is to delcare sayMeow outside of the Main function.
While we are at it…
You dont want to use the ref keyword. It has some uses. But you don’t need it in 99.9% of cases.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace c__class
{
class Program
{
public static void sayMeow (string purr) {
//purr = "meow meow";
Console.WriteLine("purr");
}
static void Main(string[] args)
{
string meow = "meow";
sayMeow(meow);
//Console.WriteLine(meow);
}
}
}
answered Oct 17, 2021 at 12:23
Cant have a method reside inside the method. Just move your sayMeow outside of the Main()
answered Oct 17, 2021 at 15:09
3
| description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
|---|---|---|---|---|---|
|
Compiler Error CS0106 |
Compiler Error CS0106 |
06/15/2017 |
CS0106 |
CS0106 |
8dec906a-ed69-4ed5-aa61-c8600d138200 |
Compiler Error CS0106
The modifier ‘modifier’ is not valid for this item
A class or interface member was marked with an invalid access modifier. The following examples describe some of these invalid modifiers:
-
The static modifier is not permitted on a local function. The static local function feature is supported starting with C# 8.0. A compiler that doesn’t support C# 8.0 produces CS0106 when you try to use this feature. However, a compiler that supports C# 8.0 but the set language version is prior to C# 8.0 will produce a diagnostic suggesting that you use C# 8.0 or later.
-
The
publickeyword is not allowed on an explicit interface declaration. In this case, remove thepublickeyword from the explicit interface declaration. -
The abstract keyword is not allowed on an explicit interface declaration because an explicit interface implementation can never be overridden.
-
Access modifiers are not allowed on a local function. Local functions are always private.
In prior releases of Visual Studio, the static modifier was not permitted on a class, but static classes are allowed starting with Visual Studio 2005.
For more information, see Interfaces.
Example
The following sample generates CS0106:
// CS0106.cs namespace MyNamespace { interface I { void M(); } public class MyClass : I { public void I.M() {} // CS0106 public static void Main() {} } }
public static void main (Args _args)
{
TmpFrmVirtual tmpFrmVirtualVend;
PurchFormLetter_Invoice purchFormLetter;
VendPackingSlipJour vendPackingSlipJour;
SysQueryRun chooseLinesQuery;
SysQueryRun chooseLinesPendingInvoiceQuery;
container conTmpFrmVirtual;
List selectedList = new List(Types::Record);
PurchId purchId = «PO00001» ; //Purchase order number
PackingSlipId packingSlipId = «PCK0001»; //Product receipt number
select firstonly vendPackingSlipJour
where vendPackingSlipJour.PurchId == purchId
&& vendPackingSlipJour.PackingSlipId == packingSlipId;
if (vendPackingSlipJour)
{
tmpFrmVirtualVend.clear();
tmpFrmVirtualVend.TableNum = vendPackingSlipJour.TableId;
tmpFrmVirtualVend.RecordNo = vendPackingSlipJour.RecId;
tmpFrmVirtualVend.NoYes = NoYes::Yes;
tmpFrmVirtualVend.Id = vendPackingSlipJour.PurchId;
tmpFrmVirtualVend.insert();
}
chooseLinesQuery = new SysQueryRun(queryStr(PurchUpdate));
chooseLinesQuery.query().addDataSource(tableNum(VendInvoiceInfoTable)).enabled(false);
// chooseLinesPendingInvoiceQuery needs to be initialized, although it will not be used
chooseLinesPendingInvoiceQuery = new SysQueryRun(queryStr(PurchUpdatePendingInvoice));
chooseLinesPendingInvoiceQuery.query().dataSourceTable(tableNum(PurchTable)).addRange(fieldNum(PurchTable,PurchId)).value(queryValue(»));
purchFormLetter = PurchFormLetter::construct(DocumentStatus::Invoice);
purchFormLetter.chooseLinesQuery (chooseLinesQuery);
purchFormLetter.parmQueryChooseLinesPendingInvoice(chooseLinesPendingInvoiceQuery);
purchFormLetter.purchTable (PurchTable::find(PurchId));
purchFormLetter.transDate (systemDateGet());
purchFormLetter.parmParmTableNum (strFmt(«%1»,packingSlipId)); //This is invoice number
purchFormLetter.printFormLetter (NoYes::No);
purchFormLetter.sumBy (AccountOrder::Auto);
purchFormLetter.specQty (PurchUpdate::PackingSlip);
while select tmpFrmVirtualVend
{
selectedList.addEnd(tmpFrmVirtualVend);
conTmpFrmVirtual = selectedList.pack();
}
purchFormLetter.selectFromJournal(conTmpFrmVirtual);
purchFormLetter.reArrangeNow(true);
purchFormLetter.run();
}
