Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot declare a body because it is marked abstract

Tags:

c#

Hi i'm new in C# console application and i'm using abstract and override but i get stack in the first method in public abstract double Compute() i got an error and it says cannot declare a body because it is marked abstract please help me. thank you!

`

abstract class Cake
    {
        public string _flavor, _size;
        public int _quantity;

        public Cake(string flavor, string size, int quantity)
        {
            _flavor = flavor;
            _size = size;
            _quantity = quantity;
        }

        public abstract double Compute()
        {
            double price;
            if(_flavor == "Chocolate" && _size == "Regular")
            {
               price = 250.50;
            }
            else if (_flavor == "Chocolate" && _size == "Large")
            {
                price = 450.50;
            }
            else if (_flavor == "Strawberry" && _size == "Regular")
            {
                price = 300.50;
            }
            else
            {
                price = 500.75;
            }
            return price;
        }
    }

    class BirthdayCake:Cake
    {
        public int _numOfCandles;

        public BirthdayCake(string flavor, string size, int quantity, int numOfCandles):base(flavor,size,quantity)
        {
            _numOfCandles = numOfCandles;
        }

        public override double Compute()
        {
            return _numOfCandles * 10.00;
        }
    }`
like image 854
Yas Smitch Avatar asked Nov 17 '17 13:11

Yas Smitch


People also ask

Why can't abstract methods have a body?

Abstract methods cannot have body. Abstract class can have static fields and static method, like other classes. An abstract class cannot be declared as final.

Can abstract class have body in C#?

Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).

What does must declare a body mean in C#?

The answer lies in the error. The Main() method doesn't have a body. A method must have a body unless you have declared this inside an interface or it is marked abstract, extern, or partial. Try replacing. C#

What is abstract overriding?

Abstract methods don't have any implementation and require non-abstract derived classes to implement them. Of course they are allowed only in abstract classes. Override allows a method to override a virtual or abstract method from its base class.


Video Answer


1 Answers

Use virtual instead of abstract when you have a default implementation but would like to allow sub-classes to override

like image 96
Pieter Geerkens Avatar answered Oct 06 '22 21:10

Pieter Geerkens