Error cs1520 class struct or interface method must have a return type

This repository contains .NET Documentation. Contribute to dotnet/docs development by creating an account on GitHub.
description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS1520

Compiler Error CS1520

07/20/2015

CS1520

CS1520

1aeeee83-52a6-45dc-b197-a9a6de3a220c

Compiler Error CS1520

Method must have a return type

A method that is declared in a class, struct, or interface must have an explicit return type. In the following example, the IntToString method has a return value of string:

class Test  
{  
    string IntToString(int i)  
    {  
        return i.ToString();  
    }  
}  

The following sample generates CS1520:

public class x  
{  
   // Method declaration missing a return type before the name of MyMethod
   // Note: the method is empty for the purposes of this example so as to not add confusion.
   MyMethod() { }
}  

And can be fixed by adding a return type to the method, such as adding void in the example below:

public class x  
{  
   // MyMethod no longer throws an error, because it has a return type -- "void" in this case.
   void MyMethod() { }
}  

Alternatively, this error might be encountered when the case of a constructor’s name differs from that of the class or struct declaration, as in the following sample. Because the name is not exactly the same as the class name, the compiler interprets it as a regular method, not a constructor, and produces the error:

public class Class1  
{  
   // Constructor should be called Class1, not class1  
   public class1()   // CS1520  
   {  
   }  
}  

See also

  • Methods
  • Constructors

It needs a return type, even if that type is void. This method declares no such type:

public SetGrade(float score)

It does, however, try to return something:

return grade;

That something appears to be a char, so make that the return type:

public char SetGrade(float score)

Though, semantically, it doesn’t seem like this should return anything. The method advertises itself as a setter, and indeed should otherwise be a normal property setter were it not for the fact that it takes a parameter. So just set the value with no return:

public void SetGrade(float score)
{
    if (score>=90.0f)
        grade='A';
    else if (score>=80.0f)
        grade='B';
    else if (score>=70.0f)
        grade='C';
    else if (score>=60.0f)
        grade='D';
    else
        grade='F';
}

(Note also that I replaced your strings like "A" with chars like 'A'. In C# you use single-quotes to make a char literal, which is very different from a string literal.)


Now, there are other issues here as well. I’ve never seen this syntax before:

private int id ();
private string name ();
private char grade ();

If those should just be variables then you don’t want parentheses:

private int id;
private string name;
private char grade;

Also, your constructor isn’t actually doing anything with the values you pass it, it just declares variables within its scope and never sets them:

public Student(int ID, string Name)
{
    int id;
    string name;
}

What you probably wanted to do there was set the class’ private variables:

public Student(int ID, string Name)
{
    id = ID;
    name = Name;
}

Though honestly you could simplify your properties using auto-generated properties. The bulk of the class would then look something like this:

class Student
{
    public int ID { get; private set; }
    public string Name { get; set; }
    public char Grade { get; private set; }

    public Student(int id, string name)
    {
        ID = id;
        Name = name;
    }

    public void SetGrade(float score)
    {
        if (score>=90.0f)
            Grade='A';
        else if (score>=80.0f)
            Grade ='B';
        else if (score>=70.0f)
            Grade ='C';
        else if (score>=60.0f)
            Grade ='D';
        else
            Grade ='F';
    }
}

This is more in keeping with C# naming conventions, reduces a lot of code, and really cleans up the overall look and feel of the class. There’s still more fixes and improvements to be made, both structurally and semantically, but I’ll leave that as an exercise for your study.

Привет, форумчане!
Хотел сделать так что бы окно при запуске появлялось в углу экрана, но столкнулся с ошибкой CS1520 «Метод должен иметь тип возвращаемого значения». Пытался найти решение в интернете, но ничего не нашёл (возможно плохо искал), поэтому хотел спросить у вас. Надеюсь на вашу помощь)
код:

using System;
using System.Drawing;
using System.Windows.Forms;
class MyButtonClass : Form
{

    private TextBox FirstText, SecondText, ThirdText;


    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // MyButtonClass
        // 
        this.ClientSize = new System.Drawing.Size(284, 261);
        this.Name = "MyButtonClass";
        this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
        this.ResumeLayout(false);

    }

    int n, k, res, v;

    public MyButtonClass()
    {
        v = 0;

        this.Width = 296;
        this.Height = 525;

        FirstText = new TextBox();
        FirstText.Top = 10;
        FirstText.Left = 0;
        FirstText.Height = 50;
        FirstText.Width = 210;
        this.Controls.Add(FirstText);
        //Declare, properties and call a TextBox

        SecondText = new TextBox();
        SecondText.Text = $"";
        SecondText.Top = 50;
        SecondText.Left = 0;
        SecondText.Height = 50;
        SecondText.Width = 210;
        this.Controls.Add(SecondText);
        //Declare, properties and call a TextBox

        ThirdText = new TextBox();
        ThirdText.Text = $"0";
        ThirdText.Top = 100;
        ThirdText.Left = 0;
        ThirdText.Height = 50;
        ThirdText.Width = 210;
        this.Controls.Add(ThirdText);
        //Declare, properties and call a TextBox

    }
    public Form()
    {
        InitializeComponent();
        this.StartPosition = FormStartPosition.Manual;
        this.Location = new Point(0, 0);
    }
    static void Main()
    {
        Application.Run(new MyButtonClass());
        //starting objects of class MyButtonClass
    }
}

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

namespace TreehouseDefense
{
class Game
{
public static void Main()
{
Map map = new Map(8, 5);

        int area = map.Width * map.Height;
    }
}

}

I’m getting the error CS1520: Class, struct, or interface method must have a return type

1 Answer

Steven Parker

My guess was right, that error was actually for line 8 of «Map.cs».

Constructor methods must have the same name as their class, but here the method name is given as «map» (with lower-case «m») instead of «Map» (with capital «M»). For that reason, it is not recognized as being a constructor; and other methods are required to have a declared return type.

Dummyn

0 / 0 / 0

Регистрация: 17.03.2019

Сообщений: 6

1

28.02.2022, 08:25. Показов 1043. Ответов 1

Метки нет (Все метки)


Ошибка возникает с конструктором Vvod, если же ставить к нему void то возникает ошибка cs0246. Как справить?

C#
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 class Komplex
 {
 double M, A; //объявление полей (модуль и аргумент)
 public Komplex (double M, double A) //Конструктор с 2 параметрами  
 {
 this.M = M;
 this.A = A;
 }
 public void Random(double M) //Конструктор с 1 параметром
 {
 var rand = new Random();
 this.M = rand.NextDouble() * 10 + 5;
 }
 public Vvod() //Конструктор по умолчанию, с помощью которого вводим значения полей с клавиатуры
 {
 Console.WriteLine("Введите Модуль");
 M = double.Parse(Console.ReadLine());
 Console.WriteLine("Введите Аргумент");
 A = double.Parse(Console.ReadLine());
 }
 
 public double mnim()
 {
return Math.Sin(A) * M; //мнимая часть
 }
 public double vech()
 {
return Math.Cos(A) * M; //вещественая часть
 }
 public void PRINT()
 {
 Console.WriteLine("Модуль и аргументnM={0}, A={1}n", M, A); //вывод
 }
 }
class Program
 {
 static void Main(string[] args)
 {
  Console.WriteLine("Введите Модуль");
  double M = double.Parse(Console.ReadLine()); 
  Console.WriteLine("Введите Аргумент");
  double A = double.Parse(Console.ReadLine());
  Vvod A1 = new Vvod(M, A);
  A1.PRINT();
  Console.WriteLine("Вещественная часть числа {0}", A1.vech());
  Console.WriteLine("Мнимая часть числа {0}", A1.mnim());
  Console.WriteLine("{0}+ {1}i", A1.vech(), A1.mnim());
 }
 }

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Kazbek17

1346 / 835 / 419

Регистрация: 06.02.2012

Сообщений: 2,603

28.02.2022, 08:48

2

Лучший ответ Сообщение было отмечено Dummyn как решение

Решение

Цитата
Сообщение от Dummyn
Посмотреть сообщение

Ошибка возникает с конструктором Vvod

Это не конструктор а метод. Конструктором класса является.

C#
1
2
3
4
public Komplex (double M, double A)
{
 
}

Так же вы пытаетесь создать метод который не имеет возвращающего типа значения, либо метод может иметь void

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void Vvod()
{
 //что то делаем.
}
//Метод с параметрами 
public void Vvod(int a, int b)
{
   //что то делаем.
}
//Метод с параметрами с возвращаемыми данными тип int
public int Vvod(int a, int b)
{
   return a;
}

На 48 строчке кода нужно вызывать класс

C#
1
2
3
4
5
6
double M = double.Parse(Console.ReadLine()); 
Console.WriteLine("Введите Аргумент");
double A = double.Parse(Console.ReadLine());
Komplex a1 = new Komplex(M,A);
//Затем можно вызывать ваш метод, с логикой обработки данных
A1.Vvod();



0



  • Remove From My Forums
  • Question

  • i write this code and i get this error(«Class, struct, or interface method must have a return type»)

    when i write same code C#1.1 not error but framework 2.0 cause this error.

    thaks for help.

    namespace Siniflar_Kalitimlar_Yapicilar
    {
        class employees
        {

                 private int _empID;
            private string _firstname;
            private string _lastname;
            private string _title;
            private double _unitprice;

                    public int empID
            {
                get { return this._empID; }
                set { this._empID = value; }
           }
            public string firstname
            {
                get { return this._firstname; }
                set { this._firstname = value; }
           }
            public string lastname
            {
                get
                {
                    return this._lastname;
                }
                set
                {
                    this._lastname = value;
                }
            }
            public string title
            {
                get
                {
                    return this._title;
                }
                set
                {
                    this.title = value;
                }
            }
            public double unitprice
            {
                get
                {
                    return this._unitprice;            
                }
                set
                {
                    this._unitprice = value;
                }

            }
              public Constructor1(int employeeID,string firstname,string lastname,string title,double unitprice)
            {
                this._empID=employeeID;
                this._firstname=firstname;
                this._lastname=lastname;
                this._title=title;
                this.unitprice=unitprice;
            }
          }
    }

Answers

  • Your class is named «employees», so the constructor for it must also be named «employees».  You named it «Constructor1», which the compile thinks it’s just a regular method, and therefore should have a return type.

C# error, when trying to execute the code as below

using System;
namespace Examples {
 class Program {
  public static void Main(string[] args) {
   Laptop Lenovo = new Laptop("Lenovo");
   Price("$");
   Processor("i");
   Ram(2);
   HDD(500);
   Laptop Dell = new Laptop("Dell");
   Price("$");
   Processor("i");
   Ram(4);
   HDD(1);
   Laptop Sony = new Laptop("Sony");
   Price("$");
   Processor("i");
   Ram(8);
   HDD(1);
  }
 }
 class Laptop: LaptopBase {
  public LaptopBase(String LaptopName): base(LaptopName) {
   this.LaptopBase = LaptopName;
  }
  class LaptopBase {
   public LaptopBase(String LaptopName) {
    WriteLine(" " + LaptopName);
   }
   public void Price() {
    WriteLine("$" + 1000, "$" + 2000, "$" + 3000);
   }
   public void Processor() {
    WriteLine("i" + 3, "i" + 5, "i" + 7);
   }
   public void Ram() {
    WriteLine(2 + "GB", 4 + "GB", 8 + "GB");
   }
   public void HDD() {
    WriteLine(500 + "GB", 1 + "TB", 1 + "TB");
   }
  }
 }
}

main.cs(31,10): error CS1520: Class, struct, or interface method must have a return type

Asked by:- Pa

0

: 4204
At:- 11/10/2017 10:24:04 AM

C#
Class
struct
or interface method must have a return type


1 Answers

Not sure what you were trying to achieve, but looking at your code, I have corrected these points to make it execute properly and have commented out the code so that you can understand

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        public static void Main(string[] args)
        {
            //Create insatce of Class with Name as "Lenove"
            Laptop Lenovo = new Laptop("Lenovo");
           
            //Using the above instance called the Price Method of Lenovo class, it will print $1000
            Lenovo.Price();
            //Using the above instance called the Price Method of Lenovo class, it will print i3
            Lenovo.Processor();
        


        }
    }
    //Laptop Class inherited from LaptopBase class
    public class Laptop : LaptopBase
    {
        public Laptop(string LaptopName) : base(LaptopName)
        {
            //this is used to set value of constructor
            this.LaptopBase = LaptopName;
        }

        public string LaptopBase { get; }
    }
    //Laptop Base class
    public class LaptopBase
    {
        public LaptopBase(String LaptopName)
        {
            //use Console.WriteLine to print data
            Console.WriteLine(" " + LaptopName);
        }

        public void Price()
        {
            Console.WriteLine("$" + 1000, "$" + 2000, "$" + 3000);
        }
        public void Processor()
        {
            Console.WriteLine("i" + 3, "i" + 5, "i" + 7);
        }
        public void Ram()
        {
            Console.WriteLine(2 + "GB", 4 + "GB", 8 + "GB");
        }
        public void HDD()
        {
            Console.WriteLine(500 + "GB", 1 + "TB", 1 + "TB");
        }
    }
}

try to execute it here online, it will work and provide you some output

0

At:- 11/10/2017 1:21:38 PM

Понравилась статья? Поделить с друзьями:
  • Error cs1519 invalid token in class record struct or interface member declaration
  • Error cs1519 invalid token float in class struct or interface member declaration
  • Error cs1514 unity
  • Error cs1514 expected
  • Error cs1513 юнити