Skip to content

Commit cede979

Browse files
Additional explanation for CS0501 (dotnet#29805)
* Update cs0501.md * Update cs0501.md * Update docs/csharp/misc/cs0501.md Co-authored-by: Bill Wagner <[email protected]>
1 parent 108ac1f commit cede979

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

docs/csharp/misc/cs0501.md

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,42 @@ ms.assetid: 3ff45208-5b9b-42f6-8a12-1eb38a665f33
1313
'member function' must declare a body because it is not marked abstract, extern, or partial
1414

1515
Nonabstract methods must have implementations.
16+
17+
## Explanation
18+
19+
In C#, methods/functions that are a part of a class must have a "body", or implementation. The compiler needs to know what should happen when these methods are called, so that it knows what to execute. A method with no body is not acceptable to the compiler because it wants to avoid confusion about the intent of the code.
20+
21+
There are exceptions to this rule:
22+
23+
* When the method is marked `abstract` as an [Abstract Method](../language-reference/keywords/abstract.md)
24+
* When the method is marked `extern` as an [External Method](../language-reference/keywords/extern.md)
25+
* When the method is marked `partial` as a [Partial Method](../language-reference/keywords/partial-method.md)
26+
27+
## Example
28+
29+
The following sample generates CS0501:
1630

17-
The following sample generates CS0501:
18-
1931
```csharp
20-
// CS0501.cs
21-
// compile with: /target:library
22-
public class clx
32+
public class MyClass
33+
{
34+
public void MethodWithNoBody(); // CS0501 declared but not defined
35+
}
36+
```
37+
38+
This could be fixed by declaring a body (by adding brackets):
39+
40+
```csharp
41+
public class MyClass
42+
{
43+
public void MethodWithNoBody() { }; // No error; compiler now interprets as an empty method
44+
}
45+
```
46+
47+
Or, using an appropriate keyword, such as defining an `abstract` method:
48+
49+
```csharp
50+
abstract class MyClass // class is abstract; classes that inherit from it will have to deifne MyAbstractMethod
2351
{
24-
public void f(); // CS0501 declared but not defined
25-
public void g() {} // OK
52+
public abstract void MyAbstractMethod(); // Compiler now knows that this method must be deinfed by inheriting classes.
2653
}
2754
```

0 commit comments

Comments
 (0)