Ошибка компилятора cs0029

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0029

Compiler Error CS0029

07/20/2015

CS0029

CS0029

63c3e574-1868-4a9e-923e-dcd9f38bce88

Compiler Error CS0029

Cannot implicitly convert type ‘type’ to ‘type’

The compiler requires an explicit conversion. For example, you may need to cast an r-value to be the same type as an l-value. Or, you must provide conversion routines to support certain operator overloads.

Conversions must occur when assigning a variable of one type to a variable of a different type. When making an assignment between variables of different types, the compiler must convert the type on the right-hand side of the assignment operator to the type on the left-hand side of the assignment operator. Take the following the code:

int i = 50;
long lng = 100;
i = lng;

i = lng; makes an assignment, but the data types of the variables on the left and right-hand side of the assignment operator don’t match. Before making the assignment the compiler is implicitly converting the variable lng, which is of type long, to an int. This is implicit because no code explicitly instructed the compiler to perform this conversion. The problem with this code is that this is considered a narrowing conversion, and the compiler does not allow implicit narrowing conversions because there could be a potential loss of data.

A narrowing conversion exists when converting to a data type that occupies less storage space in memory than the data type we are converting from. For example, converting a long to an int would be considered a narrowing conversion. A long occupies 8 bytes of memory while an int occupies 4 bytes. To see how data loss can occur, consider the following sample:

int i = 50;
long lng = 3147483647;
i = lng;

The variable lng now contains a value that cannot be stored in the variable i because it is too large. If we were to convert this value to an int type we would be losing some of our data and the converted value would not be the same as the value before the conversion.

A widening conversion would be the opposite of a narrowing conversion. With widening conversions, we are converting to a data type that occupies more storage space in memory than the data type we are converting from. Here is an example of a widening conversion:

int i = 50;
long lng = 100;
lng = i;

Notice the difference between this code sample and the first. This time the variable lng is on the left-hand side of the assignment operator, so it is the target of our assignment. Before the assignment can be made, the compiler must implicitly convert the variable i, which is of type int, to type long. This is a widening conversion since we are converting from a type that occupies 4 bytes of memory (an int) to a type that occupies 8 bytes of memory (a long). Implicit widening conversions are allowed because there is no potential loss of data. Any value that can be stored in an int can also be stored in a long.

We know that implicit narrowing conversions are not allowed, so to be able to compile this code we need to explicitly convert the data type. Explicit conversions are done using casting. Casting is the term used in C# to describe converting one data type to another. To get the code to compile we would need to use the following syntax:

int i = 50;
long lng = 100;
i = (int) lng;   // Cast to int.

The third line of code tells the compiler to explicitly convert the variable lng, which is of type long, to an int before making the assignment. Remember that with a narrowing conversion, there is a potential loss of data. Narrowing conversions should be used with caution and even though the code will compile you may get unexpected results at run-time.

This discussion has only been for value types. When working with value types you work directly with the data stored in the variable. However, .NET also has reference types. When working with reference types you are working with a reference to a variable, not the actual data. Examples of reference types would be classes, interfaces and arrays. You cannot implicitly or explicitly convert one reference type to another unless the compiler allows the specific conversion or the appropriate conversion operators are implemented.

The following sample generates CS0029:

// CS0029.cs
public class MyInt
{
    private int x = 0;

    // Uncomment this conversion routine to resolve CS0029.
    /*
    public static implicit operator int(MyInt i)
    {
        return i.x;
    }
    */

    public static void Main()
    {
        var myInt = new MyInt();
        int i = myInt; // CS0029
    }
}

See also

  • User-defined conversion operators

hi ive got this error when i tried to run but theres error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0029: Cannot implicitly convert type ‘string’ to ‘int’

 cmd.Parameters.AddWithValue("@pDateOfDelivery", po.dateOfDelivery);
                cmd.Parameters.AddWithValue("@pStatus", po.status);
                cmd.Parameters.AddWithValue("@pDeliveryTiming", po.deliveryTiming);
                cmd.Parameters.AddWithValue("@pCoID", po.coID);

                try
                {
                    conn.Open();
                    int iResult = cmd.ExecuteNonQuery();
                    if (iResult > 0)
                    {
                        result = "You have successfully updated the DeliveryOrder!";
                    }
                    else
                    {
                        result = "You have encountered an error. Please try again.";
                    }
                }
                catch (Exception)
                {
                    result = "You have encountered an error. Please try again";
                }
                finally
                {
                    cmd.Dispose();
                    conn.Close();
                }
            }
        }
        return result;
    }

Community's user avatar

asked Jun 2, 2016 at 4:00

rebecca's user avatar

1

One of your parameters is expecting an int type but you are passing string type.

Try below to convert string to int before passing.

cmd.Parameters.AddWithValue("@pCoID", Int32.Parse(po.coID));

answered Jun 2, 2016 at 4:03

Bat_Programmer's user avatar

Bat_ProgrammerBat_Programmer

6,66910 gold badges55 silver badges67 bronze badges

Use Convert.ToInt32 method to convert your string variables to integer

cmd.Parameters.AddWithValue("@pCoID",Convert.ToInt32(po.coID));

answered Jun 2, 2016 at 4:05

mohsen's user avatar

mohsenmohsen

1,7333 gold badges17 silver badges54 bronze badges

1

You Should use cmd.Parameters.Add() So that you can specify the expecting Datatype;

The DataType of the parameter will be OdbcType if you are using OdbcCommands and are of SqlDbType if you are using SqlCommand. In short the datatype will be depand on the type of command. here is an example with SqlDbType.

 cmd.Parameters.Add("@", SqlDbType.Int).Value = po.coID;

Make sure that po.coID is of integer type. or else you need to convert it to an integer; I would like to suggest Int32.TryParse() for this conversion

answered Jun 2, 2016 at 4:20

sujith karivelil's user avatar

sujith karivelilsujith karivelil

28.6k6 gold badges54 silver badges87 bronze badges

I need convert String of input of table database to Integer value in C# .NET 4 and tried this code inspired from this Link:

    int i;
    string Entry_Level = Convert.ToInt32("2,45");
    i = Convert.ToInt32(Entry_Level); 

But I’ve this error:

Compiler Error Message: CS0029: Cannot implicitly convert type ‘int’ to ‘string’

EDIT

Solved with:

    decimal i;
    string Entry_Level = "2,45";
    i = Convert.ToDecimal(Entry_Level);

    Response.Write(i.ToString());
    Response.End();

In output I’ve 2,45, many thanks!

Mong Zhu's user avatar

Mong Zhu

23.2k10 gold badges43 silver badges76 bronze badges

asked Apr 14, 2014 at 8:49

Chevy Mark Sunderland's user avatar

8

string Entry_Level = Convert.ToInt32("2,45");

should be

string Entry_Level = "2,45";

Why not go for this though:

int i = 2,45;

But since this is not an integer, you’ll need one of the built-in decimal types:

/* use this when precision matters a lot, for example when this is a unit price or a percentage value that will be multiplied with big numbers */
decimal i = 2.45 


/*  use this when precision isn't the most important part. 
It's still really precise, but you can get in trouble when dealing with really small or really big numbers. 
Doubles are fine in most cases.*/
double i = 2.45 

See this thread for more information about decimal vs double.

Community's user avatar

answered Apr 14, 2014 at 8:50

Moeri's user avatar

4

The value 2,45 does not represent an integer. It is a real value. So I believe that you are actually looking for Convert.ToDouble or Convert.ToDecimal. Or perhaps double.Parse or decimal.Parse.

You may also need to consider what happens when you run your code on a machine that does not use , as the decimal separator. Consider using the overloads that accept IFormatProvider.

answered Apr 14, 2014 at 8:53

David Heffernan's user avatar

David HeffernanDavid Heffernan

599k42 gold badges1064 silver badges1481 bronze badges

try this one

string Entry_Level = Convert.ToInt32("2,45").toString()

answered Apr 14, 2014 at 9:02

harits nurrois's user avatar

You can use the line of code below which will remove your compile error but it will through and Runtime Exception cause 2,45 is not a valid integer.

string Entry_Level = Convert.ToInt32("2,45").ToString(); 

I will suggest you to write the below line of codes which will help you to get the value 2.45 on your variable named i

decimal i;
string Entry_Level = "2,45";
Entry_Level = Entry_Level.Replace(',', '.');
i = Convert.ToDecimal(Entry_Level);  

Mong Zhu's user avatar

Mong Zhu

23.2k10 gold badges43 silver badges76 bronze badges

answered Apr 14, 2014 at 9:15

Md.Rajibul Ahsan's user avatar

Здраствуйте.
Начну с того что сразу скажу что исправление при помощи
throw new NotImplementedException();
которое предлагает VS Code не подойдёт тк при использовании combobox поментально кидает к ошибке…

Form1.cs:

using static SDM_Lab5.PasMove;

namespace SDM_Lab5
{
    public partial class Form1 : Form
    {
        Aeroplane aero;
        Train tr;
        Avto av;
        public Form1()
        {
            InitializeComponent();

        }
        PasMove pm;
        
        Gorod[] towns; 
        string pathString = @"C:UsersMisteDesktopЗадания_СИ(шарп)ЛабораторныеЛР_5SDM_Lab5SDM_Lab5img";

        private void Form1_Load(object sender, EventArgs e)
        {
            aero = new Aeroplane(); // создаем экземпляры классов с начальными значениями
            tr = new Train();
            av = new Avto();
            towns = new Gorod[5]; // Задаем значения полей 
            towns[0] = new Gorod("Москва", 709, "Moscow.jpg");
            towns[1] = new Gorod("Рим", 3016, "Rome.jpg");
            towns[2] = new Gorod("Нью-Йорк", 6883, "New-york.jpg");
            towns[3] = new Gorod("Токио", 7598, "Tokyo.jpg");
            towns[4] = new Gorod("Лондон", 2818, "London.jpg");

            
            //  добавим поле Name из каждого объекта в выпадающий список          
            for (int i = 0; i < 5; i++)
            { comboBox1.Items.Add(towns[i].Name); }

        }
        int k;
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            k = comboBox1.SelectedIndex;
            // выводим расстояние до нужного города
            label1.Text = towns[k].ToString();
            // выводим соответствующую картинку          
            pictureBox1.Image = Image.FromFile(pathString + "\" + towns[k].Url);

        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox2.Text == "")
            { MessageBox.Show("Не выбран транспорт!"); return; }
            Form2 frm2 = new Form2(pm);
            frm2.ShowDialog();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBox2.SelectedIndex)
            {
                case 0: pm = aero; break; // Ошибки здесь, у aero; tr; av
                case 1: pm = tr; break;
                case 2: pm = av; break;
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (comboBox1.Text == "" || comboBox2.Text == "")
            { MessageBox.Show("Не выбраны данные для расчета"); return; }
            else
            {
                double g = pm.Time(towns[k].Rast);
                double c = (pm.Equals(av)) ? pm.CostTrip(towns[k].Rast) : pm.CostTrip(g);
                label1.Text = string.Format("Стоимость поездки на 1 человека {0:f2} (без учета прочих сборов)", c);
            }

        }
    }
}

PasMove.cs:

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

namespace SDM_Lab5
{
    public class PasMove
    {
       
        public virtual int CountPas { get; set; }
        public virtual double Speed { get; set; }
        public string Name { get; set; }
        public double CostFuel { get; set; }
        public double Rashod { get; set; }
        public double Time(double s)
        { return s / Speed; }
        public virtual double CostTrip(double t)
        { return t * Rashod * CostFuel / CountPas; }

        public class Aeroplane
        {
            int countPas;
            double speed;

            public int CountPas
            {
                get { return countPas; }
                set { if (value <= 300) countPas = value; }
            }
            public double Speed
            {
                get => speed;
                set { if (value > 600 && value <= 900) speed = value; }
            }
            string Name;
            double CostFuel;
            double Rashod;
            public Aeroplane()
            {
                Name = "Самолет";
                CountPas = 280;
                Speed = 800;
                CostFuel = 37.2;
                Rashod = 2600;
            }

        }
        public class Train
        {
            int countPas;
            double speed;

            public int CountPas
            {
                get { return countPas; }
                set { if (value <= 300) countPas = value; }
            }
            public double Speed
            {
                get => speed;
                set { if (value > 600 && value <= 900) speed = value; }
            }
            string Name;
            double CostFuel;
            double Rashod;
            public Train()
            {
                Name = "Поезд";
                CountPas = 500;
                Speed = 80;
                CostFuel = 3.2;
                Rashod = 1600;

            }

        }
        public class Avto
        {
            int countPas;
            double speed;

            public int CountPas
            {
                get { return countPas; }
                set { if (value <= 300) countPas = value; }
            }
            public double Speed
            {
                get => speed;
                set { if (value > 600 && value <= 900) speed = value; }
            }
            double CostFuel;
            double Rashod;

            public virtual double CostTrip(double t) { return t / 100 * Rashod * CostFuel / CountPas;}
            string Name;
            public  Avto()
            {
                
                Name = "Автомобиль";
                CountPas = 3;
                Speed = 110;
                CostFuel = 3.2;
                Rashod = 1600;

            }
        }
    }
}

628cc57c46943979581608.png
Извините что всё так конкретно и всё сразу не могу найти решение уже 2 дня :(

0 / 0 / 0

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

Сообщений: 9

1

07.06.2019, 03:45. Показов 9763. Ответов 3


Студворк — интернет-сервис помощи студентам

Пишу ргз по проге и вылезает вот такая ошибка

CS0029 Не удается неявно преобразовать ConsoleKeyInfo в ConsoleSpecialKey



0



Эксперт .NET

6316 / 3935 / 1577

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

Сообщений: 9,237

07.06.2019, 04:01

2

Вам же русским языком компилятор пишет что выражения справа и слева от знака = имеют разные, несовместимые типы, с указанием имен этих самых типов…
А дальше у вас используется не объявленная переменная (имена переменных регистрозависимы)…



0



0 / 0 / 0

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

Сообщений: 9

07.06.2019, 04:20

 [ТС]

3

можно какое нибудь решение этой ошибки?)



0



Someone007

Эксперт .NET

6316 / 3935 / 1577

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

Сообщений: 9,237

07.06.2019, 04:26

4

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

Решение

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

можно какое нибудь решение этой ошибки?)

А если немного подумать и исправить ошибку самому?

C#
1
ConsoleKeyInfo key = Console.ReadKey(true);



0



I get to help a lot of people learn C# programming every year. As I watch new developers grow and get used to working in C# and Visual Studio, it has become fairly clear to me that reading C# compiler errors and even their documentation is an acquired skill. I’ve made a request for Microsoft to improve the error message feedback in Visual Studio, but until that’s resolved developers still have a tough time working through early obstacles.

Because of this, I’m creating this unusual post to serve as beginner-friendly documentation to what I personally view as the most likely compiler errors a new developer is likely to encounter. Microsoft has wonderful documentation on compiler errors, and this is something that will help you out significantly as you grow, but early on a paragraph or two aimed at a beginner can be exactly what you need.

I also snuck in a few of the more interesting compiler errors I noticed about the maximum limits of the C# compiler, so even if you’re very familiar with C# at this point you’ll likely still learn a few things skimming this list.

Take a look at my list and my recommendations on these issues and let me know if you find this helpful or encounter something I missed.

CS0003 – Out of Memory

This occurs when a computer runs out of memory compiling your code. Close any unnecessary programs and reboot the machine if the problem persists.

CS0004 – Warning Treated as Error

Developers may configure projects to treat certain warnings as errors. These warnings may be specified in the build section of the project’s properties. Typically it is best to resolve the specific warning listed in the build errors since someone wanted that to be treated severely.

CS0015 – Type Name too Long

.NET requires the names of types and namespaces to be less than 1024 characters. If you find yourself getting this error, you may want to reconsider your team’s naming choices.

CS0017 – More than one entry point defined

This occurs when your program has more than one class defined with a static void main method. Remove one of them or manually set the project’s startup object in the project properties.

CS0019 – Operator ‘operator’ cannot be applied to operands of type ‘type’ and ‘type’

This occurs when you try to compare two different types in ways that cannot be compared. For example, checking to see if integer values are equal to Boolean values, subtracting a string from a number, etc. This error often occurs when developers forget what type of data is stored by a particular variable.

CS0020 – Division by Constant Zero

This occurs if you try to force a division by zero in your code. You cannot force a division by zero through a numeric literal or by using a constant for the denominator, but you can declare a variable holding 0 and use that as a denominator.

CS0021 – Cannot apply indexing to type

This occurs when you try to use an array or list-style indexer on a type that doesn’t support it. This often occurs when developers assume they’re working with an array, string, or list and are not.

CS0023 – Operator ‘operator’ cannot be applied to operand of type ‘type’

This occurs when you try to use a mathematical operator with a type that doesn’t support it. For example, trying to generate a negative value of a string. Double check that your variables are of the type you think they are and re-evaluate what you are trying to do.

CS0026 – Keyword this cannot be used in a static method

This error occurs when you are working inside of a static method and try to use the this keyword. Static methods are methods associated with the class itself and not with an instance of the class. As a result, static methods do not have access to any properties, methods, or fields on the class that are not static.

CS0029 – Cannot implicitly convert type ‘type’ to ‘type’

This occurs when you have a variable of one type and are trying to store it into a variable of another type. Some types allow you to automatically convert from one type to another (an implicit conversion), but the types you are using do not support that. You may need to use an explicit cast using (type) syntax.

CS0030 – Cannot convert type ‘type’ to ‘type’

This occurs when there is no implicit or explicit conversion between two different types. If you’re sure you need to do what you’re doing, you could create a method to convert from one type to the other.

CS0031 – Constant value ‘value’ cannot be converted to a ‘type’.

This occurs when you try to store a value into a variable type that cannot store that particular value. For example, if you try to store 5 billion into an integer (which can store values up to around 2.1 billion) you will get this compiler error. You can resolve this error by storing the value into a type that can hold larger values, such as a long.

CS0050 – Inconsistent accessibility: return type ‘type’ is less accessible than method ‘method’

This occurs when a method returns a type that has a visibility or access modifier that is more restrictive than the method and class the method is currently in. For example this error will occur if a public method in a public class returns a type that is defined as internal.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0051 – Inconsistent accessibility: parameter type ‘type’ is less accessible than method ‘method’

This occurs when a method takes in a parameter that is of a type that has a visibility or access modifier that is more restrictive than the method and class the method is currently in. For example this error will occur if a public method in a public class requires a parameter of a type that is defined as internal.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0052 – Inconsistent accessibility: field type ‘type’ is less accessible than field ‘field’

This occurs when a class has a public field that is of a type that has a visibility or access modifier that is more restrictive than the class the method is currently in. For example this error will occur if a class has a public field of a type that is defined as internal.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0053 – Inconsistent accessibility: property type ‘type’ is less accessible than property ‘property’

This occurs when a class has a property of a type that has a visibility or access modifier that is more restrictive than the property’s visibility. For example this error will occur if a public property is of a type that is defined as internal.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0060 – Inconsistent accessibility: base class ‘class1’ is less accessible than class ‘class2’

This occurs when a class inherits from another class but the subclass’s access modifier is less restrictive than the base class’s access modifier. For example this error will occur if a public class inherits from an internal class.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0061 – Inconsistent accessibility: base interface ‘interface 1’ is less accessible than interface ‘interface 2’

This occurs when an interface inherits from another interface but the child interface’s access modifier is less restrictive than the base interface’s access modifier. For example this error will occur if a public interface inherits from an internal interface.

This error usually occurs when developers forget to mark an interface as public. Remember that interfaces have a default access modifier of internal when no access modifier is specified, although every member of an interface is public. Typically the fix for this is to explicitly declare that interface as public.

CS0100 – The parameter name ‘parameter name’ is a duplicate

This occurs when a developer declares a method but uses the same parameter name twice in the method’s parameter list. The fix for this is generally to remove an unneeded parameter or to rename parameters so that all parameters have a different name.

CS0101 – The namespace ‘namespace’ already contains a definition for ‘type’

This occurs when a class is defined twice in the same namespace. This can occur when a class is renamed but the old file still exists, when a developer forgot to mark a class as part of a different namespace, or when a developer intended to use the partial keyword but forgot to specify it. The fix for this will vary based on which files you want and what namespaces they should live in.

CS0102 – The type ‘type name’ already contains a definition for ‘identifier’

This occurs when you declare a member such as a field twice in the same class. Often this is a symptom of using an existing variable name instead of choosing a new name.

CS0103 – The name ‘identifier’ does not exist in the current context

This error often occurs when trying to use a variable defined in another scope. This commonly occurs when you try to define a variable inside of a try block and refer to it in a catch block, when there was no guarantee that the runtime was able to create that variable and therefore the variable is not available.

The fix for this is typically to declare the variable before the try / catch block and update its value from the try block. In this way the catch block will get either the initial value of the variable or its updated value and will be able to reference it.

CS0111 – Type ‘class’ already defines a member called ‘member’ with the same parameter types

This occurs when a developer creates a duplicate method or property with an identical signature consisting of a return type and parameter types. The compiler detects that there will not be a way for code outside of the class to distinguish between one member and the other and so this error is raised. Typically when this occurs you need to either rename one of the two members, change the parameters of one of the methods, or merge the two methods together into one method.

CS0117 – ‘type’ does not contain a definition for ‘identifier’

This occurs when you are trying to call a method or use a property on an instance of an object, but there is no method or property with that name. This can be an issue with capitalization, spelling, or forgetting the name of the member you’re referring to. Code completion can help you find the correct name to use.

CS0120 – An object reference is required for the non-static field, method, or property ‘member’

This often occurs in static methods when you attempt to work with non-static members of the same class. Remember that static methods are associated with the class itself and not with a specific instance of that class. As a result, static methods cannot access properties, fields, and methods that are not marked as static.

The fix for this is often to remove the static keyword from the method that needs to access instance variables. This is counter-intuitive since the compiler pushes you towards adding static in other places, but if you follow that path to its logical conclusion all of your data becomes static eventually, so you’re better off removing the static keyword when confronted by this.

CS0122 – ‘member’ is inaccessible due to its protection level

This occurs when you are trying to call a method or use a property on an instance of an object, but that member is defined as private or protected and you are outside of the class or something that inherits from it. You may not be intended to work with the method or property you are using and you should probably look for public members that might meet your needs without compromising the class’s encapsulation.

CS0127 – Since ‘function’ returns void, a return keyword must not be followed by an object expression

This is a rarer error that occurs when you are in a method defined as void but are trying to return a specific object. Remember that void methods do not return any value so a return statement should just be listed as return;. If you find that you do need to return a value, you should change the return type of the method from void to some specific type.

CS0128 – A local variable named ‘variable’ is already defined in this scope

This occurs when you re-declare a variable that already exists. The solution for this is to either use a different variable name or to remove the type name from your statement and change it from a variable declaration to an assignment statement and re-use the existing variable.

This error often comes from copying and pasting code that declares a new variable.

CS0133 – The expression being assigned to ‘variable’ must be constant

This occurs when you are declaring a const and declaring it to another variable. Constants are evaluated at the time your code is compiled and the compiler will not know the value of your variables. As a result, constants must be set to a literal number or string value.

CS0134 – ‘variable’ is of type ‘type’. A const field of a reference type other than string can only be initialized with null.

This occurs when you are trying to declare a const of a type other than a numeric or string value. Typically, if you have a const that needs to store a reference type you should instead use readonly which is less optimized than a const but works with reference types and ensures that the value will never change.

CS0136 – A local variable named ‘var’ cannot be declared in this scope because it would give a different meaning to ‘var’, which is already used in a ‘parent or current/child’ scope

This occurs when you declare a new variable with the same name as another variable in a visible scope. The solution for this is to either use a different variable name or to remove the type name from your statement and change it from a variable declaration to an assignment statement and re-use the existing variable.

CS0145 – A const field requires a value to be provided

This occurs when you declare a const but do not provide a value. You should set a const equal to some string or numeric variable when declaring it.

CS0150 – A constant value is expected

This occurs when the compiler requires a constant value such as a numeric or string literal but a variable is defined. This can occur when you use a variable in a switch statement or when you are using an array initializer for an array with a variable size.

Switch statements cannot use cases for specific variables, though switch expressions are more flexible.

When working with arrays of varying size, you may want to avoid the use of array initializers and instead manually set the elements of the array after creation.

CS0152 – The label ‘label’ already occurs in this switch statement

This occurs when you duplicate a case statement inside of a switch statement. Typically this occurs when you didn’t notice the case already existed and you can delete your repeated case statement.

CS0160 – A previous catch clause already catches all exceptions of this or of a super type (‘type’)

The ordering of catch statements in a try / catch matters since the runtime will try to match the first catch that applies to the exception it encountered. Because of this, the compiler generates this error if it sees a more specific exception type after a less specific exception type since this results in a case where the more specific catch statement could never be reached.

Move your more specific catch statement above the less specific one to fix this error.

CS0161 – Not all code paths return a value

This occurs because the C# compiler believes that it is possible to get to the end of your method without encountering a return statement. Keep in mind that the C# compiler does very little inferences based on your if statements and even if it may not actually be possible to reach the end of the method without returning, the compiler still thinks it is.

The fix for this is almost always to add a final return statement.

CS0165 – Use of unassigned local variable

This occurs when the compiler sees a variable that is defined but not set to an initial value and determines that the value of that variable needs to be read from later on in the method before the variable is guaranteed to have its value set.

The fix for this is generally to set the variable to be equal to an initial value.

CS0176 – Static member ‘member’ cannot be accessed with an instance reference; qualify it with a type name instead

This occurs when you have a static property or field on a class but are trying to refer to it on a specific instance of that class.

Use the class name instead of the instance variable to access the static member.

CS0201 – Only assignment, call, increment, decrement, and new object expressions can be used as a statement

This typically occurs when you are performing some sort of mathematical operation but not storing the result into a variable. The compiler understands the operation but sees it has no value, so it raises the error.

The fix for this is to store the result of the mathematical operation into a variable or to remove the unnecessary line.

CS0204 – Only 65534 locals are allowed

Apparently you have a method that has over 65 thousand local variables inside of it. The compiler doesn’t like this very much and, frankly, I’m a little concerned why you’d need that many.

Reconsider your life choices.

CS0230 – Type and identifier are both required in a foreach statement

This occurs when you are writing a foreach statement without specifying all parts of the statement.

foreach statements require a variable type, a variable name, the word in, and some variable that can be enumerated over. For example: foreach (string person in people)

CS0234 – The type or namespace name ‘name’ does not exist in the namespace ‘namespace’ (are you missing an assembly reference?)

This occurs when you are trying to refer to a type via its fully-qualified name, including the namespace, but no known type exists with that namespace and type name. This can be a spelling error, a mistake as to which namespace the type lives in, or a correct namespace and type, but your project does not yet have a reference to the project the type is defined in.

If your spelling and namespaces are correct you may need to add a project reference to your project or install a package via nuget.

CS0236 – A field initializer cannot reference the non-static field, method, or property ‘name’.

This occurs when you try to define a field by referencing another field. This error exists to prevent unpredictable behavior based on which field initializers run first.

The fix for this is to set the value of the field in the constructor instead of in a field initializer.

CS0246 – The type or namespace name ‘type/namespace’ could not be found (are you missing a using directive or an assembly reference?)

This occurs when you are trying to refer to a type no known type exists with that type name in the using statements currently in your file.

This is usually a spelling error or a missing using statement at the top of your file.

If your spelling and using statements are correct you may need to add a project reference to your project or install a package via nuget.

CS0266 – Cannot implicitly convert type ‘type1’ to ‘type2’. An explicit conversion exists (are you missing a cast?)

This occurs when you are trying to store a variable of one type into a variable of another type without casting. For example, if you are trying to set a double value into an int variable you will see this error.

The statement “an explicit conversion exists (are you missing a cast)” is telling you that these types are compatible, but the compiler wants to make sure you intend to convert from one to another so it requires you to cast your variable from one type to another.

You cast variables in C# by using parentheses around a type name like this: int num = (int)myDouble;

CS0500 – ‘class member’ cannot declare a body because it is marked abstract

This occurs when you declare an abstract member inside of an abstract class, but you tried to give it a method body (using {}). Abstract members do not have method bodies.

Remove the  {}’s from your abstract method. Alternatively, if you want to provide a default implementation and allow inheriting classes to optionally override yours, use virtual instead of abstract.

CS0501 – ‘member function’ must declare a body because it is not marked abstract, extern, or partial

This occurs when you try to declare a method but forget to give it a method body with {}’s.

This can also occur when you mean to define an abstract method but forgot to use the abstract keyword.

CS0506 – ‘function1’ : cannot override inherited member ‘function2’ because it is not marked “virtual”, “abstract”, or “override”

In C# you have to mark a method as virtual or abstract to be able to override it.

The fix for this is usually to add the virtual keyword to the method in the base class.

CS0507 – ‘function1’ : cannot change access modifiers when overriding ‘access’ inherited member ‘function2’

When overriding a method you must keep the same access modifier as the base method. If the access modifier needs to change, change it in all classes that have the method.

CS0508 – ‘Type 1’: return type must be ‘Type 2’ to match overridden member ‘Member Name’

When overriding a method you cannot change the return type of the method. If you think you need to return something radically different, you may need to introduce a new method instead of overriding an existing one. Alternatively, creative uses of interfaces or inheritance can allow you to return a more specific version of something from a method through polymorphism.

CS0513 – ‘function’ is abstract but it is contained in nonabstract class ‘class’

When you need a method to be abstract, the entire class needs to be abstract as well.

CS0525 – Interfaces cannot contain fields

This one is self-explanatory. An interface is a contract that defines what members need to be present. Fields in classes should be private and are implementation details that do not belong in an interface.

CS0526 – Interfaces cannot contain constructors

This one is self-explanatory. An interface is a contract that defines what members need to be present on an already-constructed class. Interfaces do not care about how an instance is created and cannot denote constructors required for a given class.

CS0531 – ‘member’ : interface members cannot have a definition

This occurs when you try to give an interface member a method body. Interfaces denote capabilities that must be in place, not how those capabilities should work.

If you think you really need a default implementation of a method, you might want to use an abstract class instead of an interface.

CS0534 – ‘function1’ does not implement inherited abstract member ‘function2’

This occurs when you inherit from an abstract class that has abstract members but do not override those members. Because of this, the compiler has no implementation for those abstract members and does not know how to handle them if they are called.

Override the inherited member or mark the inheriting class as abstract as well.

CS0535 – ‘class’ does not implement interface member ‘member’

This occurs when you implement an interface but have not provided members that match those defined in the interface. Members must match the exact type signatures of those defined in the interface and should have names that match those in the interface as well.

CS0645 – Identifier too long

This occurs when you try to name a variable or other identifier something longer than 512 letters long.

What exactly are you trying to do over there that has you naming variables this long?

CS0844 – Cannot use local variable ‘name’ before it is declared.

This occurs when you try to use a variable in a method above when that variable is declared. C# does not have hoisting like some other languages do and variables are only available after they are declared.

Reorder your statements to match your needs.

CS1001 – Identifier expected

This usually occurs when you forget the name of a variable, class, or parameter but have defined other aspects of that line of code. Check some reference materials for what you are trying to do because you’re missing something important.

CS1002 – Semicolon expected

C# requires you to end most statements with a semicolon, including this one. Add a semicolon to the end of the line and all should be well.

CS1026 – ) expected

You have too many opening parentheses and not enough closing parentheses. Check to make sure that all open-parentheses have a matching closing parentheses.

Clicking on a parentheses in Visual Studio will highlight the matching parentheses making it easier to spot the one you’re missing.

CS1033 – Source file has exceeded the limit of 16,707,565 lines representable in the PDB; debug information will be incorrect

What on earth are you even doing over there? Why would you have a source file that requires more than 16 million lines?

Don’t do that. Just no. It’s time to hire a consultant.

CS1034 – Compiler limit exceeded: Line cannot exceed ‘number’ characters

Some people like tabs. Some people like spaces. You, apparently solve this debate by removing line breaks entirely.

You should never need to have a line of code longer than 16 million characters.

CS1035 – End-of-file found, ‘*/’ expected

Your code has a block comment start (/*) but no matching end comment. Add an end comment (*/) and the compiler will be happier.

CS1039 – Unterminated string literal

It looks like you started a string somewhere but forgot to put the other quotation mark. Add it in where it needs to be.

CS1501 – No overload for method ‘method’ takes ‘number’ arguments

This occurs when you are trying to call a method with an incorrect number of arguments or parameters to that method. Check the code or documentation for the method you’re trying to call and ensure you have the correct number of arguments specified.

CS1513 – } expected (missing closing scope)

You have too many opening curly braces and not enough closing curly braces. Check to make sure that all open curly braces have a matching closing curly brace.

Clicking on a { in Visual Studio will highlight the matching } making it easier to spot the one you’re missing.

CS1514 – { expected

Your code requires a { but you didn’t provide one. This often happens after declaring a namespace or class. Check your syntax and add curly braces where they need to go.

CS1525 – Invalid expression term ‘character’

This error seems ambiguous, but most of the time when I see this error it comes from someone trying to use == to assign a value to a variable instead of using the = operator. If this is not your error, you may need to consult some documentation or reference material for valid syntax for what you’re trying to do.

CS1552 – Array type specifier, [], must appear before parameter name

This error occurs when you put [] syntax around the variable name and not around the type name when declaring an array.

Write your arrays as int[] myArray; instead of int myArray[];.

CS1604 – Cannot assign to ‘variable’ because it is read-only

This occurs when you’ve declared a readonly or const variable and are trying to set its value. You can’t do that. If you need to change its value, it can’t be readonly or const.

CS7036 – No argument given that corresponds to the required formal parameter (incorrect method call)

This error occurs when trying to call a base constructor but not specifying a parameter that is required by that constructor.

Double check your base() call and make sure the number and types of parameters lines up with a specific constructor present on your base class.

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора cs0021
  • Ошибка компиляции для платы esp32 dev module
  • Ошибка компилятора c3867
  • Ошибка компиляции для платы doit esp32 devkit v1
  • Ошибка компилятора c3861