简体   繁体   中英

Noob Concern: Problems making a new void method. C#

I am trying to make a method in a new class that I made...

public void CalcDrinks(bool HealthOption) 
{
    if (HealthOption)
    {
        CostOfBeverage = 5M; 
    }
    else
    {
        CostOfBeverage = 20M; 
    }
}

And I keep getting a red squiggly under the void saying... "expected class, delegate, enum, interface or struct error"

I'm not sure what I am missing...

You would get that precisely that error if the method is declared outside of a class.

namespace Blah
{
    public void CalcDrinks(bool HealthOption) 
    {
        if (HealthOption)
        {
            CostOfBeverage = 5M; 
        }
        else
        {
            CostOfBeverage = 20M; 
        }
    }
}

In this snippet, there is no class definition to be seen. Fix it to the below and see that it compiles.

public class Foo
{
    private decimal CostOfBeverage;

    public void CalcDrinks(bool HealthOption)
    {
        if (HealthOption)
        {
            CostOfBeverage = 5M;
        }
        else
        {
            CostOfBeverage = 20M;
        }
    }
}

Make sure the method is inside a class, and that the class/property/other method braces before and after the method line up. Also make sure that the previous statement has a ; (semicolon).

This problem normally occurs because you have mismatched braces before the method or you have a missing semi-colon:

Correct

namespace A
{
    public class AA
    {
        public string B {get; set; }    
        public string C {get; set; }
        public void ShowD()
        {
            DoSomething;
        }

    }
}

Incorrect

namespace A
{
    public class AA
    {
        public string B { get; set; }      
        public string C {get; set;    // <--Note missing brace)
        public void ShowD()
        {
            DoSomething;
        }

    }
}

You're missing some code in your sample, but based on the error message, your function is declared outside of your class. The code for your method must be nested within your class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM