Error cs0126 an object of a type convertible to int is required

C# Compiler Error CS0126 – An object of a type convertible to 'type' is required and solution to fix it in visual studio.

C# Compiler Error

CS0126 – An object of a type convertible to ‘type’ is required

Reason for the Error

You will receive this error when the signature of a property specifies the return type and you don’t return the value of the specified type in your C# code.

For example, try compiling the below code snippet.

namespace DeveloperPublishNamespace
{
    public class Employee
    {
        public int Name
        {
            set
            {
            }
            get
            {
                return;  
            }
        }
    }

    public class DeveloperPublish
    {
        public static void Main()
        { 
        }
    }
}

We have an Employee class with the property “Name”. The property has a getter which just calls return without specifying the value or type that it needs to return. This will result in the below error.

Error CS0126 An object of a type convertible to ‘int’ is required ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 12 Active

C# Error CS0126 – An object of a type convertible to 'type' is required

Solution

When you are using a getter for a property, ensure that you return the value too.

This is my code:

namespace Cinemaseats

 {public partial class MainForm : Form
    {
    private const int numOfSeats = 60;
    private int numOfReservedSeats = 0;
    Seat currentSeat = new Seat();
    public MainForm()
    {
        InitializeComponent();
        InitializeGUI();
    }

    private void InitializeGUI()
    {
        radioButton1.Checked = true;
        namn.Text = string.Empty;
        pris.Text = string.Empty;
    }
    private void button1_Click(object sender, EventArgs e)
    {
        **int seatNr = ReadAndValidateSeatNr();**

        if (seatNr < 0)
        {
            MessageBox.Show("Välj ett föremål från listan");
            return;
        }

        if (radioButton2.Checked)
            ReserveSeat(seatNr);
        else
            CancelSeat(seatNr);

        UpdateGUI(seatNr);
    }

    public int GetnumOfSeats()
    {
        return numOfSeats;
    }

    **public int ReadAndValidateSeatNr()
    {
     thelist.Items.Add(test); //test
     return;
    }
    string test = Convert.ToString(2);
}**
}

I have converted my string «test» to an int but still VS says that the return value has to be an int? I want to display 60 «seats in my listbox, that is to say «Seat 1″,»Seat 2» and so on. I wrote a test string to see if I could make it work.I’m not sure how getter and setters methods work but I have figured otu that I would need them here?

Chris Ballard's user avatar

asked Mar 18, 2014 at 12:33

Essej's user avatar

1

In your ReadAndValidateSeatNr() function you are not returning anything:

public int ReadAndValidateSeatNr()
{
     thelist.Items.Add(test); //test
     return;  //<--------- here nothing is being returned
}

My compiler gives the same error to me :P

enter image description here

Change return to void if you do not need to return anything:

public void ReadAndValidateSeatNr()
{
     thelist.Items.Add(test); //test
     //return; redundant statement - not even required in this case
}

If your requirement is something like 1 for "Seat 1", etc — go for an enum:

enum my_enum{ Seat1=1, Seat2= 2};

public int ReadAndValidateSeatNr()
{
        switch(test)
        {
             case "Seat 1":
             thelist.Items.Add(test); //test
             return (int)my_enum.Seat1;

             case "Seat 2":
             thelist.Items.Add(test); //test
             return (int)my_enum.Seat2;
        }
}

answered Mar 18, 2014 at 12:35

Sadique's user avatar

SadiqueSadique

22.4k7 gold badges64 silver badges91 bronze badges

6

If you don’t want to return something in the ReadAndValidateSeatNr method you should change it like this:

public void ReadAndValidateSeatNr() 
{
    thelist.Items.Add(test);
}

Patrick Hofman's user avatar

answered Mar 18, 2014 at 12:37

Pascal_AC's user avatar

Pascal_ACPascal_AC

5313 silver badges16 bronze badges

A method can either return an int or a string (to say only one type). As other have suggested either change the return type to void if you do not want to return any thing.

If your problem is only having «Seat» string at the beginning, then you should not add the item to list box inside the method. Instead return an int from the method and add the item to your list box by doing something like this from the main block.

thelist.Items.Add(«Seat » + ReadAndValidateSeatNr().ToString());

In this case your method will be retuning an int and can be used independently and you will still be able to add to your list box in the format you want it.

answered Mar 18, 2014 at 12:50

Yatish's user avatar

YatishYatish

1233 silver badges12 bronze badges

The first function to be called in any C# program is Main. We can have as many as four different ways to declare Main in our program. This article gets you started with an entry point into your first C# application.

We can have as many as four different ways to declare Main in our program. They are as follows:

static void Main() {...}
static int Main() {...}
static void Main(string[] a) {...}
static int Main(string[] args) {...}

The operating system calls Main and waits for it to return a value. This value denotes the success or failure of the program.

Main can either return a number or result in no return value, that is, void. If it returns an int, by convention, a value of zero means success and any other value indicates an error. No international authority can standardize the error numbers, it largely depends on the programmer himself.

Copy as a command takes two parameters; the source and destination files. Similarly, a C# program can also accept command line parameters at runtime. The executable testapp.exe can be entered as

C:>testapp one two three

testapp.cs:

class zzz {
	public static void Main(string[] a) {
		int i;
		for (i = 0; i < a.Length; i++)
		System.Console.WriteLine(a[i]);
	}
}

Output:

one
two
three 

one, two, three are called command line parameters. The program accepts them in an array of strings. As the array is a parameter to the function, we are free to decide on its name. Every array has a member called Length, which tells us the size of the array. In our case, it is three. Thus, a[0] will contain the first word one and not the name of the program, a[1] will contain two and a[3] – three. Main now behaves like any other function. What we do next with the command line arguments depends entirely upon us.

testapp.cs:

class zzz {
	public static void Main(string[] a) {}
	public static int Main() {}
}

Compiler Error:

testapp.cs(3,20): error CS0017: Program 'testapp.exe' has
more than one entry point defined: 'zzz.Main(string[])'
testapp.cs(6,19): error CS0017: Program 'testapp.exe' has
more than one entry point defined: 'zzz.Main()'

You can have one and only one function called Main in any C# program. Even though you can call it with different parameters, with the name changing, Main as a function must be given only once.

testapp.cs:

class zzz {
	public static void Main(int i) {}
}

Compiler Warning:

testapp.cs(3,21): warning CS0028: 'zzz.Main(int)' has the
wrong signature to be an entry point

Compiler Error:
error CS5001: Program 'testapp.exe' does not have an entry point defined

Here, the compiler first displays a warning that Main has not been created with the right parameters. The error, following the warning, proclaims that we have forgotten to create a function called Main. The signature includes the return type only in special cases as entry point.

testapp.cs:

class zzz {
	public static long Main() {
		return 0;
	}
}

Compiler Warning:

testapp.cs(3,20): warning CS0028: 'zzz.Main()' has
the wrong signature to be an entry point

Compiler Error:

error CS5001: Program 'testapp.exe' does not have an
entry point defined

The signature refers to the parameters given to the function plus the return value. Main in the above program returns ‘long’, hence we see the error.

testapp.cs:

class zzz {
	public void Main() {}
}

Compiler Error:
error CS5001: Program 'testapp.exe' does not have an entry point defined

The signature also includes modifiers
like static etc. It just proves the importance of the function Main and the way it has been defined.

testapp.cs

class zzz {
	public static void Main() {}
}
class yyy {
	public static void Main() {}
}

Compiler Error:

testapp.cs(2,21): error CS0017: Program 'testapp.exe' has
more than one entry point defined: 'zzz.Main()'
testapp.cs(8,21): error CS0017: Program 'testapp.exe' has
more than one entry point defined: 'yyy.Main()'

The error proves the point that you cannot have two different classes, zzz and yyy, containing Main. Only one occurrence of Main is allowed. You always have only one chance of a lifetime. Ditto with Main.

testapp.cs:

class zzz {
	private static void Main() {
		System.Console.WriteLine("hell");
	}
}

Output:
hell

The access modifiers are not included within the signature for Main. Even though Main is made private, it is considered as an entry point function, hence hell gets displayed. This function is unique and works as a special case.

testapp.cs:

public static void Main() {
	System.Console.WriteLine("hell");
}
class zzz {}

Compiler Error:
testapp.cs(1,15): error CS1518: Expected class, delegate, enum, interface, or struct

You cannot create a function outside a class or a structure. This rule has to be strictly adhered to even for Main.

testapp.cs:

public class zzz {
	public static int Main() {
		return;
	}
}

Compiler Error:

testapp.cs(5,1): error CS0126: An object of a type
convertible to 'int' is required

In this example, the function Main has to return an int and we are not returning any value with the keyword return. The compiler tries to convert a nothing into an int and hence the error. This is a generic error that occurs whenever the compiler tries to convert a data type into another and is not successful.

testapp.cs:

class zzz {
	public static int Main() {}
}

Compiler Error:

testapp.cs(3,19): error CS0161: 'zzz.Main()': not all code paths
return a value

The compiler’s error messages need the services of an editor. The function Main should return an int, but we forgot to do so. This results in an error. Thus whenever an entity should return a value, we should return such a data type or be prepared for an error.

Written by: dimport.
Published by: thinkt4nk.
Many thanks to Kamran Shakil for this article.

Я уверен, что это что-то глупое и простое, но я не могу этого понять. Следующий код:

public GameObject AISelectCannon() {
    Debug.Log("AISelectCannon called");
    GameObject desiredCannon = AIController.selectCannon(0);
    if (desiredCannon.tag.Contains("Cannon")) return;
    m_SelectedCannon = desiredCannon;
    aiSelectionPending = true;
    return m_SelectedCannon;
}

Выдает следующую ошибку:

Scripts/CubeContainer.cs(61,59): error CS0126: An object of a type convertible to `UnityEngine.GameObject' is required for the return statement

(GameObject desireCannon …. это строка 61)

Другая важная информация от AIController:

public static GameObject selectCannon(int side) {

Так что да, есть идеи?

1 ответ

Лучший ответ

Ваш первый оператор return ничего не возвращает, он просто говорит return

if (desiredCannon.tag.Contains("Cannon")) return // return something


0

JRowan
11 Окт 2014 в 08:34

Понравилась статья? Поделить с друзьями:
  • Error cs0120 an object reference is required for the non static field method or property
  • Error cs0119 gameobject is a type which is not valid in the given context
  • Error cs0119 expression denotes a type where a variable value or method group was expected
  • Error cs0118 editor is a namespace but is used like a type
  • Error cs0117 unity