C# Compiler Error
CS0501 – ‘member function’ must declare a body because it is not marked abstract, extern, or partial
Reason for the Error
You’ll get this error in your C# code when you try to declare a function without a body.
For example, let’s try to compile the below C# code snippet.
using System; namespace DeveloperPublishNamespace { public class Employee { public void SetId(); } class Program { static void Main(string[] args) { Console.WriteLine("No Error"); } } }
You’ll receive the error code CS0501 because the C# compiler has detected that you have declared a non-abstract method SetId() without the method body.
Error CS0501 ‘Employee.SetId()’ must declare a body because it is not marked abstract, extern, or partial DeveloperPublish C:UsersSenthilsourcereposConsoleApp4ConsoleApp4Program.cs 6 Active
Solution
Non-abstract methods in C# must have a method body or implementation. You can fix this error in your C# program by adding the implementation or method body when declaring the function.
using System; namespace DeveloperPublishNamespace { public class Employee { public void SetId() { // Logic } } class Program { static void Main(string[] args) { Console.WriteLine("No Error"); } } }
So I have been coding C# for a few days, making a Roblox Exploit. I am making a drop down menu for my exploit, using timer ticks and it says «CS0501 C# must declare a body because it is not marked abstract, extern, or partial». I am a newbie at C# so I searched the problem up and I am not able to figure out why this problem is occurring. The code is down below. Please help, and if so, put down the code so I can just see what was my problem! Thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeAreDevs_API;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public void LuaTimer_Tick(EventArgs e, object sender);
private ExploitAPI wolfapi = new ExploitAPI();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
wolfapi.LaunchExploit();
}
private void buttonKill_Click(object sender, EventArgs e)
{
string target = usernameTarget.Text;
wolfapi.DoKill(target);
}
private void button1_Click_1(object sender, EventArgs e)
{
string target = usernameTarget.Text;
int speedValue = Int32.Parse(SpeedValue.Text);
wolfapi.SetWalkSpeed(target, speedValue);
}
private void button3_Click(object sender, EventArgs e)
{
string target = usernameTarget.Text;
wolfapi.TeleportMyCharacterTo(target);
}
private void speedValue_TextChanged(object sender, EventArgs e)
{
}
private void updateButton_Click(object sender, EventArgs e)
{
wolfapi.IsUpdated();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void button1_Click_2(object sender, EventArgs e)
{
string script = luaExecutor.Text;
wolfapi.SendLimitedLuaScript(script);
}
private void luaC_Click(object sender, EventArgs e)
{
string script = luaExecutor.Text;
wolfapi.SendScript(script);
}
private void noDoors_Click(object sender, EventArgs e)
{
}
private void luaExecutor_TextChanged(object sender, EventArgs e)
{
}
private void luaPanel_Paint(object sender, PaintEventArgs e)
{
}
private void luaOpen_Click(object sender, EventArgs e)
{
}
private void LuaTimer_Tick_1(object sender, EventArgs e)
{
}
}
}
-
Question
-
User-1392235324 posted
Dear All
When I converted this code from Console Application to Web I got this problem:
CS0501: ‘_Default.Student.First.get’ must declare a body because it is not
marked abstract or externLine 27: public string First { get; set; }
The following is the code of C# file:
using System; using System.Collections.Generic; using System.Linq; using System.Text; public partial class _Default : System.Web.UI.Page { protected void Load_Page(object sender, EventArgs e) { // Create the query. // The first line could also be written as "var studentQuery =" IEnumerable<Student> studentQuery = from student in students where student.Scores[0] > 90 select student; // Execute the query. // var could be used here also. foreach (Student student in studentQuery) { Response.Write("<br/>" + student.Last + ", " + student.First); } } public class Student { public string First { get; set; } public string Last { get; set; } public int ID { get; set; } public List<int> Scores; } // Create a data source by using a collection initializer. static List<Student> students = new List<Student> [ new Student [First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> [97, 92, 81, 60]], new Student [First="Claire", Last="O’Donnell", ID=112, Scores= new List<int> [75, 84, 91, 39]], new Student [First="Sven", Last="Mortensen", ID=113, Scores= new List<int> [88, 94, 65, 91]], new Student [First="Cesar", Last="Garcia", ID=114, Scores= new List<int> [97, 89, 85, 82]], new Student [First="Debra", Last="Garcia", ID=115, Scores= new List<int> [35, 72, 91, 70]], new Student [First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> [99, 86, 90, 94]], new Student [First="Hanying", Last="Feng", ID=117, Scores= new List<int> [93, 92, 80, 87]], new Student [First="Hugo", Last="Garcia", ID=118, Scores= new List<int> [92, 90, 83, 78]], new Student [First="Lance", Last="Tucker", ID=119, Scores= new List<int> [68, 79, 88, 92]], new Student [First="Terry", Last="Adams", ID=120, Scores= new List<int> [99, 82, 81, 79]], new Student [First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> [96, 85, 91, 60]], new Student [First="Michael", Last="Tucker", ID=122, Scores= new List<int> [94, 92, 91, 91]], new Student [First="Abdulkari", Last="Alabdulwahab", ID=122, Scores= new List<int> [100, 100, 100, 100]] ]; }
How can I solve this problem?!
Answers
-
User-1392235324 posted
Now solved by adding to Web.Config:
<system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="WarnAsError" value="false"/> </compiler> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="OptionInfer" value="true"/> <providerOption name="WarnAsError" value="false"/> </compiler> </compilers> </system.codedom>
And changed .CS file to:
using System; using System.Collections.Generic; using System.Linq; using System.Text; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Create the query. // The first line could also be written as "var studentQuery =" IEnumerable<Student> studentQuery = from student in students where student.Scores[0] > 90 select student; // Execute the query. // var could be used here also. foreach (Student student in studentQuery) { Response.Write("<br/>" + student.Last + ", " + student.First); } } public class Student { public string First { get; set; } public string Last { get; set; } public int ID { get; set; } public List<int> Scores; } // Create a data source by using a collection initializer. static List<Student> students = new List<Student> { new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}}, new Student {First="Claire", Last="O’Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}}, new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}}, new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}}, new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}}, new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}}, new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}}, new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}}, new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}}, new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}}, new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}}, new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91}}, new Student {First="Abdulkari", Last="Alabdulwahab", ID=122, Scores= new List<int> {100, 100, 100, 100} } }; }
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
using System; namespace Test { class Point { static void Main(string[] args); // Поля: int x, y; int x, y; // Конструкторы, позволяющие создать экземпляр класса: с нулевыми координатами; с заданными координатами. public Point(int x = 0, int y = 0) { this.x = x; this.y = y; } // Методы, позволяющие: вывести координаты точки на экран; public void Show() { Console.WriteLine("x = {0}, y = {1}", x, y); } // рассчитать расстояние от начала координат до точки; public double Origin() { return Math.Sqrt(x * x + y * y); } // переместить точку на плоскости на вектор (a, b). public void Displacement(int x, int y) { this.x += x; this.y += y; } // Свойства: получить-установить координаты точки (доступное для чтений и записи); public int X { set { x = value; } get { return x; } } public int Y { set { y = value; } get { return y; } } // позволяющие умножить координаты точки на скаляр (доступное только для записи). public int MultScalX { set { x *= value; } } public int MultScalY { set { y *= value; } } // Перегрузку: операции ++ (--): одновременно увеличивает (уменьшает) значение полей х и у на 1; public static Point operator --(Point obj) { obj.x -= 1; obj.y -= 1; return obj; } public static Point operator ++(Point obj) { obj.x += 1; obj.y += 1; return obj; } // констант true и false: обращение к экземпляру класса дает значение true, если значение полей x и у совпадает, иначе false; public static bool operator false(Point obj) { if (obj.x != obj.y) return false; return true; } public static bool operator true(Point obj) { if (obj.x == obj.y) return true; return false; } // операции бинарный +: одновременно добавляет к полям х и у значение скаляра; public static Point operator +(Point obj, int scal) { obj.x += scal; obj.y += scal; return obj; } public static Point operator +(int scal, Point obj) { obj.x += scal; obj.y += scal; return obj; } // Индексатор, позволяющий по индексу 0 обращаться к полю x, по индексу 1 – к полю y, при других значениях индекса выдается сообщение об ошибке. public int this[int i] { get { if (i == 0) return x; if (i == 1) return y; throw new Exception("Error"); } } // преобразования типа Point в string (и наоборот). public static explicit operator String(Point obj) { return obj.x + ", " + obj.y; } public static explicit operator Point(string str) { string[] q = str.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); Point obj = new Point(); obj.x = int.Parse(q[0]); obj.y = int.Parse(q[1]); return obj; } } } |