Hi

I want to make an abstract method. But I always get the error " cannot declare a body because it is marked abstract."
When I delete the return then I get the error than I need a return.

can someone help me please

public  abstract Graphics drawRectangle(Graphics drawarea)
        {
          return drawarea;
        }

Dani AI

Generated

Short expert follow-up to clarify and give concrete fixes.

As and pointed out, the compiler error comes from marking a method abstract but also giving it a body. You have three clean options depending on intent:

  1. Declare a contract (no implementation). Make the containing class abstract and leave the method as a signature (no body). A derived, non-abstract class must override and provide the implementation:
public abstract class ShapeBase
{
    public abstract void Draw(Graphics g);
}

public class MyRectangle : ShapeBase
{
    public override void Draw(Graphics g)
    {
        // actual drawing here
    }
}
  1. Provide a default implementation in the base class. Use virtual (or just a normal method) so the base can implement behavior and derived classes may override:
public class ShapeBase
{
    public virtual void Draw(Graphics g)
    {
        // default drawing or no-op
    }
}
  1. Keep a body but change the signature if you don’t need to return a Graphics object. If the method just uses the passed-in Graphics surface, prefer void (you rarely need to return the same Graphics reference):
public virtual void DrawRectangleOn(Graphics g)
{
    // draw on g; no return needed
}

Practical tips: use PascalCase method names (e.g., DrawRectangle), put abstract members only in abstract classes, and don’t mark abstract members static. If you obtain a Graphics yourself (via CreateGraphics), remember to dispose it; if you’re passed e.Graphics from Paint, just draw and return void.

Recommended Answers

All 2 Replies

The very definition of an abstract method in C# is a function declaration without an implementation. Non-abstract derived classes are required to provide the implementation. If you want to provide a default implementation, the method should be virtual rather than abstract.

If you want to keep it abstract just replace the body with a semicolon. That makes it a declaration rather than a definition:

public abstract Graphics drawRectangle(Graphics drawarea);

Abstract method cannot have any code implementation.
Only overriden from it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.