Error cs0029 cannot implicitly convert type void to int

Ошибка компилятора CS0029 Не удается неявно преобразовать тип «type» в «type» Компилятору требуется явное преобразование. Например, может потребоваться приведение r-значения к тому же типу, который имеет l-значение. Или может быть необходимо предоставить подпрограммы преобразования для поддержки перегрузки определенных операторов. Преобразование должно выполняться в том случае, когда переменная одного типа присваивается переменной другого типа. При […]

Содержание

  1. Ошибка компилятора CS0029
  2. Name already in use
  3. docs / docs / csharp / language-reference / compiler-messages / cs0029.md
  4. Error cs0029 cannot implicitly convert type void to int
  5. Answered by:
  6. Question
  7. Answers
  8. All replies
  9. Error cs0029 cannot implicitly convert type void to int
  10. Answered by:
  11. Question
  12. Answers
  13. All replies

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

Не удается неявно преобразовать тип «type» в «type»

Компилятору требуется явное преобразование. Например, может потребоваться приведение r-значения к тому же типу, который имеет l-значение. Или может быть необходимо предоставить подпрограммы преобразования для поддержки перегрузки определенных операторов.

Преобразование должно выполняться в том случае, когда переменная одного типа присваивается переменной другого типа. При присвоении между переменными разных типов компилятор должен преобразовать тип в правой части оператора присваивания в тип в его левой части. Рассмотрим следующий код:

i = lng; выполняет присваивание, однако типы данных переменных в левой и правой частях оператора присваивания не совпадают. Прежде чем выполнять присваивание, компилятор неявно преобразует переменную lng типа long в тип int. Выполнение этого преобразования не предписывается явно какими-либо инструкциями кода и поэтому называется неявным. Обратите внимание, что в этом коде реализуется неявное сужающее преобразование, которое не допускается компилятором из-за риска потери данных.

Преобразование является сужающим в тех случаях, когда целевой тип данных занимает в памяти меньше места, чем исходный. Например, сужающим является преобразование из long в int. Тип long занимает в памяти 8 байт, а тип int — 4 байта. Ниже показан пример потери данных в результате такого преобразования:

Переменная lng содержит слишком большое значение, которое нельзя сохранить в переменной i . Таким образом, при преобразовании этого значения в тип int потеряется часть данных, а преобразованное значение не будет в точности равно исходному.

Расширяющие преобразования являются противоположностью сужающих. В этом случае целевой тип данных занимает в памяти больше места, чем исходный. Ниже приведен пример расширяющего преобразования:

Обратите внимание на отличие этого примера кода от первого. На этот раз переменная lng находится в левой части оператора присваивания и является его целевой переменной. Перед присвоением компилятор должен неявно преобразовать переменную i типа int в тип long. Это будет расширяющее преобразование, поскольку исходный тип (int) занимает в памяти 4 байта, а целевой (long) — 8 байт. Неявные расширяющие преобразования не связаны с риском потери данных и допускаются к применению. Любое значение типа int может быть сохранено в переменной типа long.

Поскольку неявные сужающие преобразования не допускаются, для успешной компиляции этого кода необходимо явно выполнить преобразование типа данных. Явные преобразования выполняются путем приведения типов. Понятие приведения типов в языке C# описывает преобразование одного типа в другой. Чтобы гарантировать успешную компиляцию кода, необходимо использовать следующий синтаксис:

В третьей строке кода содержится инструкция для явного преобразования переменной lng типа long в тип int перед выполнением присвоения. Помните, что при сужающем преобразовании существует риск потери данных. Сужающие преобразования следует использовать с осторожностью, поскольку даже в случае успешной компиляции кода во время выполнения могут быть получены непредвиденные результаты.

Приведенная здесь информация относится только к типам значений. При использовании типов значений вы работаете напрямую с данными, хранящимися в переменной. Но в .NET также есть ссылочные типы. В случае с ними вы работаете не с фактическими данными, а со ссылками на переменные. Например, к ссылочным типам относятся классы, интерфейсы и массивы. Неявные или явные преобразования между ссылочными типами не поддерживаются кроме случаев, когда компилятор допускает конкретные преобразования или реализованы соответствующие операторы преобразования.

В следующем примере возникает ошибка CS0029:

Источник

Name already in use

docs / docs / csharp / language-reference / compiler-messages / cs0029.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

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:

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:

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:

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:

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.

Источник

Error cs0029 cannot implicitly convert type void to int

Answered by:

Question

where is the problem?

Answers

>> for (int j=arrcolid.Length-1;j=0;j—)

Well, that’s easy.

j=0 is an assignment, which evaluates to 0 (int)

j==0 is a comparison, which evaluate to t/f (bool)

What type is strupcolid? Are you sure that’s the line that’s causing your problem? That particular line of code should compile just fine assuming strupcolid is a string.

Why does this line end in a semicolon, is this watching something in another thread ? If so, there are much better ways to do that.

As someone said, this line cannot cause that error, not as it’s posted here. != will return a bool. You could try breaking it up into more than one line, and see where the problem is then.

I don’t know what you are doing wrong, but the following code does NOT generate the error for me:

static void Main( string [] args)
<
string strupcolid = «0»;
while ((System.Convert.ToInt32(strupcolid)!=0))
;
>

thank you very much for your advice.

I am very sorry to say that due to carelessness or other reasons, I mistakingly regard this line as error line.

Actually the error line is:

>> for (int j=arrcolid.Length-1;j=0;j—)

Well, that’s easy.

j=0 is an assignment, which evaluates to 0 (int)

j==0 is a comparison, which evaluate to t/f (bool)

= and ==, haha, I am too careless to mind the difference.

[CS0029: Cannot implicitly convert type ‘int’ to ‘string’

Line 31: txtBillingPhone.Text= reader.GetInt32(1);

where is the problem?

akkusayed wrote:

[CS0029: Cannot implicitly convert type ‘int’ to ‘string’

Line 31: txtBillingPhone.Text= reader.GetInt32(1);

where is the problem?

Impossible to answer without knowing the type of «reader».

Well, I’m pretty sure that a property called «Text» is going to be a string property, and I’m pretty sure that a method called GetInt32() is going to return an Int32, which means you are trying to assign an int to a string, which, sure enough, will produce exactly the error you are getting.

Источник

Error cs0029 cannot implicitly convert type void to int

Answered by:

Question

where is the problem?

Answers

>> for (int j=arrcolid.Length-1;j=0;j—)

Well, that’s easy.

j=0 is an assignment, which evaluates to 0 (int)

j==0 is a comparison, which evaluate to t/f (bool)

All replies

What type is strupcolid? Are you sure that’s the line that’s causing your problem? That particular line of code should compile just fine assuming strupcolid is a string.

Why does this line end in a semicolon, is this watching something in another thread ? If so, there are much better ways to do that.

As someone said, this line cannot cause that error, not as it’s posted here. != will return a bool. You could try breaking it up into more than one line, and see where the problem is then.

I don’t know what you are doing wrong, but the following code does NOT generate the error for me:

static void Main( string [] args)
<
string strupcolid = «0»;
while ((System.Convert.ToInt32(strupcolid)!=0))
;
>

thank you very much for your advice.

I am very sorry to say that due to carelessness or other reasons, I mistakingly regard this line as error line.

Actually the error line is:

>> for (int j=arrcolid.Length-1;j=0;j—)

Well, that’s easy.

j=0 is an assignment, which evaluates to 0 (int)

j==0 is a comparison, which evaluate to t/f (bool)

= and ==, haha, I am too careless to mind the difference.

[CS0029: Cannot implicitly convert type ‘int’ to ‘string’

Line 31: txtBillingPhone.Text= reader.GetInt32(1);

where is the problem?

akkusayed wrote:

[CS0029: Cannot implicitly convert type ‘int’ to ‘string’

Line 31: txtBillingPhone.Text= reader.GetInt32(1);

where is the problem?

Impossible to answer without knowing the type of «reader».

Well, I’m pretty sure that a property called «Text» is going to be a string property, and I’m pretty sure that a method called GetInt32() is going to return an Int32, which means you are trying to assign an int to a string, which, sure enough, will produce exactly the error you are getting.

Источник

Adblock
detector

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

koddchan

0 / 0 / 0

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

Сообщений: 1

1

29.08.2018, 17:36. Показов 6260. Ответов 2

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


Пишу Roblox Exploit (чит на игру)

делаю всё как на видео, почти

тут 2 одинаковых cs0029 ошибки

C#
1
2
3
4
5
       private void button8_Click(object sender, EventArgs e)
        {
            string script = richTextBox1; 
            api.SendScript(script);
        }

пользуюсь 2017 visual studio

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



0



910 / 795 / 329

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

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

29.08.2018, 17:47

2

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

Решение

1) по коду ошибки благополучно находится информация как её исправить
2) Вы присваиваете переменной типа string целый контрол richTextBox, что вы от этого ожидаете?
3) если Вам нужен текст что внутри richTextBox так и обращайтесь и получайте его в переменную string script = richTextBox1.Text;



1



Someone007

Эксперт .NET

6269 / 3897 / 1567

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

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

29.08.2018, 17:47

3

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

Решение

C#
1
string script = richTextBox1.Text;



1



Понравилась статья? Поделить с друзьями:
  • Error cs0029 cannot implicitly convert type string to unityengine ui text
  • Error cs0029 cannot implicitly convert type string to bool
  • Error cs0029 cannot implicitly convert type int to string
  • Error cs0029 cannot implicitly convert type int to bool
  • Error cs0029 cannot implicitly convert type float to unityengine vector3