开发者

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... "exp开发者_Go百科ected 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜