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?
CodePudding user response:
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://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions
CodePudding user response:
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.
CodePudding user response:
Yes because you are declaring it as a local function for Main and the only available modifiers for local functions are async, unsafe, static or extern. See documentation : https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions#local-function-syntax
Consider declaring it as a method memeber for the Program class, outside the scope of the Main method.
CodePudding user response:
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);
}
}
}
CodePudding user response:
Cant have a method reside inside the method. Just move your sayMeow outside of the Main()