Error cs0029 cannot implicitly convert type float to unityengine vector3

error CS0029: Cannot implicitly convert type `UnityEngine.Transform’ to `UnityEngine.Vector3′ using UnityEngine; using System.Collections; using FSM; > i created a fsm context that gets the transform and sets it as the direction. what i am trying to do get my character to move on its own the error i am having is converting it. also […]

Содержание

  1. error CS0029: Cannot implicitly convert type `UnityEngine.Transform’ to `UnityEngine.Vector3′
  2. 2 Ответов
  3. Ваш Ответ
  4. Welcome to Unity Answers
  5. Подписаться на вопрос

error CS0029: Cannot implicitly convert type `UnityEngine.Transform’ to `UnityEngine.Vector3′

using UnityEngine; using System.Collections; using FSM;

> i created a fsm context that gets the transform and sets it as the direction. what i am trying to do get my character to move on its own the error i am having is converting it. also i am not sure if the way i am doing it will work. t$$anonymous$$s is in my context——

public Transform gettransform() < return Controller.transform; >public void setcontroller(Transform pos) < pos = Controller.transform;
>

2 Ответов

Ответ от Julien-Lynge · 08/03/12 22:17

I’m sorry, I couldn’t read your code (you didn’t format it nicely). However, just glancing at it, your problem is that a Transform is not a Vector3. A transform is all the position, rotation, scaling, etc. information for an object. Instead of using Vector3 whatever = transform;, you likely need to use Vector3 whatever = transform.position;

transform.position is the position of the object, and is a Vector3. Likewise, transform.scale is a Vector3, and transform.rotation is a quaternion.

Ответ от mpavlinsky · 08/03/12 22:20

I don’t know anyt$$anonymous$$ng at all about FSM but it seems like you should be doing

Ваш Ответ

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Подписаться на вопрос

Ответы Ответы и комментарии

6 пользователей подписаны.

Источник

какая то ошибка

PaRtIzAn_MaXs Дата: Воскресенье, 08 Декабря 2013, 03:24 | Сообщение # 1

почетный гость

Сейчас нет на сайте

Cannot convert «int» to «unityEngine.Vector3»
Вот скрипт

Код

var grabPower = 10.0;
var throwPower = 50;
var hit : RaycastHit;
var RayDistance : float = 3.0;
private var Grab : boolean = false;
private var Throw : boolean = false;
var offset : Transform;

function Update () {
if(Input.GetMouseButtonDown(1)){

Physics.Raycast(transform.position, transform.forward, hit, RayDistance);
if(hit.rigidbody);
Grab = true;
}
}
if(Input.GetMouseButtonDown(0)){
if(Grab){
if(hit.rigidbody);
hit.rigidbody.velocity = (offset.position — (hit.transform.position + hit.rigidbody.centerOfMass))* grabPower;
}
}
if(Throw){
if(hit.rigidbody){
hit.rigidbody.velocity = transform.forward = throwPower;
Throw = false;
}
}



C#-Unity3D

JHawk Дата: Воскресенье, 08 Декабря 2013, 08:39 | Сообщение # 2

めゃくちゃちゃ

Сейчас нет на сайте

ОМГ……….. ты INTEGER приравниваешь к VECTOR3.
Ищи, в какой строчке ошибка и исправляй сам, ибо нет желания копаться в твоем коде.

Добавлено (08.12.2013, 08:39)
———————————————
З.Ы, найти ошибку можно двойным кликом по ней в консольке.

robertono Дата: Воскресенье, 08 Декабря 2013, 12:15 | Сообщение # 3

Чокнутый Кот

Сейчас нет на сайте

PaRtIzAn_MaXs,
Я не знаю как учишь написание скриптов ты, но я :
1) Больше не беру чужие коды
2) Пишу только свой код, может большой и не оптимизированный но свой

И тебе так же советую)

White9 Дата: Воскресенье, 08 Декабря 2013, 12:35 | Сообщение # 4

заслуженный участник

Сейчас нет на сайте

Код

hit.rigidbody.velocity = transform.forward = throwPower;

Вот здесь ошибка. Измени тип throwPower на Vector3 и задай именно как вектор. И мне кажется, что из-за такого присваивания тоже будет ошибка

Сообщение отредактировал White9Воскресенье, 08 Декабря 2013, 12:35

robertono Дата: Воскресенье, 08 Декабря 2013, 12:42 | Сообщение # 5

Чокнутый Кот

Сейчас нет на сайте

Цитата White9 ()

И мне кажется, что из-за такого присваивания тоже будет ошибка

конечно)

seaman Дата: Воскресенье, 08 Декабря 2013, 12:58 | Сообщение # 6

старожил

Сейчас нет на сайте

PaRtIzAn_MaXs, хочешь совет?
Учись сам находить ошибки. Иначе постоянно будешь просить на форуме найти их и тем самым ухудшать и без того не очень хорошее мнение о себе.
Как искать?
1. Внимательно читать что пишет Юнити. В консоли обычно пишется достаточно для того, чтобы определить где ошибка и в чем она заключается. Например:

Цитата

Assets/Move.cs(21,30): error CS0029: Cannot implicitly convert type `float’ to `UnityEngine.Vector3′

Что мы тут видим. Имя скрипта, в котором ошибка (Move.cs), строка и столбец в котором ошибка (21,30) и собственно текст ошибки.
2. Смотрим скрипт и место в нем где выдало ошибку.

Код

transform.position = test = t;

3. Переводим сообщение — не может косвенно конвертировать `float’ в `UnityEngine.Vector3
4. Пытаемся сопоставить сообщение об ошибке и код. Ищем где тут float, где тут Vector3. Первое — это t, второе test и position.
5. Понимаем, что НЕЛЬЗЯ присвоить переменную типа float вектору.
6. Думаем — а что же мы тут вообще хотели сделать?
БИНГО! Мы хотели просто в позицию записать вектор УМНОЖЕННЫЙ на константу!
Пишем правильный код
У Вас это будет… Подумайте сами.

Добавлено (08.12.2013, 12:58)
———————————————

Цитата

И мне кажется, что из-за такого присваивания тоже будет ошибка

Не совсем понял, что Вы имеет в виду, но можно писать два равенства подряд, типа:

Код

Vector3 throwPower = Vector3.zero;
hit.rigidbody.velocity = transform.forward = throwPower;

Ошибки быть не должно.

Сообщение отредактировал seamanВоскресенье, 08 Декабря 2013, 12:58

robertono Дата: Воскресенье, 08 Декабря 2013, 13:05 | Сообщение # 7

Чокнутый Кот

Сейчас нет на сайте

Цитата seaman ()

о можно писать два равенства подряд, типа:

Цитата seaman ()

hit.rigidbody.velocity = transform.forward = throwPower;

Серьезно? blink

seaman Дата: Воскресенье, 08 Декабря 2013, 13:08 | Сообщение # 8

старожил

Сейчас нет на сайте

Попробуйте. В шарпе точно работает.
PaRtIzAn_MaXs Дата: Воскресенье, 08 Декабря 2013, 13:16 | Сообщение # 9

почетный гость

Сейчас нет на сайте

Цитата robertono ()

PaRtIzAn_MaXs,
Я не знаю как учишь написание скриптов ты, но я :
1) Больше не беру чужие коды
2) Пишу только свой код, может большой и не оптимизированный но свой

И тебе так же советую)

У меня не получается учить.я и переписываю и учу и всё равно ничего не выходит


C#-Unity3D

JHawk Дата: Воскресенье, 08 Декабря 2013, 13:19 | Сообщение # 10

めゃくちゃちゃ

Сейчас нет на сайте

Потому что ты ТУПОЙ школота!!!!

Добавлено (08.12.2013, 13:19)
———————————————
Только школота начинает вайнить на форуме, если у него что то не получается!

PaRtIzAn_MaXs Дата: Воскресенье, 08 Декабря 2013, 13:20 | Сообщение # 11

почетный гость

Сейчас нет на сайте

Цитата JHawk ()

Потому что ты ТУПОЙ школота!!!!
Добавлено (08.12.2013, 13:19)
———————————————
Только школота начинает вайнить на форуме, если у него что то не получается!

И ты был школотой.То что я в школе ничего не значит


C#-Unity3D

robertono Дата: Воскресенье, 08 Декабря 2013, 13:45 | Сообщение # 12

Чокнутый Кот

Сейчас нет на сайте

Цитата JHawk ()

школота

Цитата PaRtIzAn_MaXs ()

в школе

Цитата PaRtIzAn_MaXs ()

И ты был школотой

Добавлено (08.12.2013, 13:45)
———————————————

Цитата PaRtIzAn_MaXs ()

У меня не получается учить.я и переписываю и учу и всё равно ничего не выходит

Попробуй сделать как я : забить на гейм дев на 1 год, обдумать свои поступки и потом в него вернутся и лучше не возвращятся…

Сообщение отредактировал robertonoВоскресенье, 08 Декабря 2013, 13:44

JHawk Дата: Воскресенье, 08 Декабря 2013, 14:15 | Сообщение # 13

めゃくちゃちゃ

Сейчас нет на сайте

robertono, КОКОКОКОКОМБО!!!!!!!!
Короче по теме.
PaRtIzAn_MaXs, иди крестиком вышивай, возвращайся в геймдев через n-дцать лет.
White9 Дата: Воскресенье, 08 Декабря 2013, 14:17 | Сообщение # 14

заслуженный участник

Сейчас нет на сайте

Цитата seaman ()

Попробуйте. В шарпе точно работает.

Спасибо, просто ни разу так не делал )

Adom Дата: Воскресенье, 08 Декабря 2013, 14:39 | Сообщение # 15

Печенька!

Сейчас нет на сайте

PaRtIzAn_MaXs, Мне 13 лет но ведь у меня не плохо получается писать свои скрипты а почему у тебя то не получается ?
seaman Дата: Воскресенье, 08 Декабря 2013, 14:44 | Сообщение # 16

старожил

Сейчас нет на сайте

Потому что неправильно учится. Тут или нужно иметь способности приличные и тогда можно учится как угодно, или нужно учиться последовательно.
Забыть на какое то время о Юнити. Взять книгу по программированию для новичков, посмотреть видеоуроки по шарпу. И желательно не просто просмотреть, а выполнить все задания не подглядывая в ответы из книги.
Уже потом вернуться к Юнити.

Сообщение отредактировал seamanВоскресенье, 08 Декабря 2013, 14:44

White9 Дата: Воскресенье, 08 Декабря 2013, 14:50 | Сообщение # 17

заслуженный участник

Сейчас нет на сайте

seaman, а можешь что-нибудь посоветовать? В магазине видел только книги с самыми-самыми азами или без упражнений.
Просто в универе мы программирование проходили довольно поверхностно (не затрагивали работу с классами, наследованием, паттернами и прочим). Точнее в теории что-то было, а на практике не применяли

Сообщение отредактировал White9Воскресенье, 08 Декабря 2013, 14:51

Adom Дата: Воскресенье, 08 Декабря 2013, 14:51 | Сообщение # 18

Печенька!

Сейчас нет на сайте

seaman, Угусь а я в первое время копался в Unity что да как потом начал смотреть уроки и потом потихоньку начал писать мелкие скрипты а потом больше и больше ))
JHawk Дата: Воскресенье, 08 Декабря 2013, 15:47 | Сообщение # 19

めゃくちゃちゃ

Сейчас нет на сайте

seaman, что бы уметь писать коды, надо логически мыслить. Изходя из этого мы имеем, что что бы быть хорошим программистом надо быть неплохим математиком, а значит что либо PaRtIzAn_MaXs слишком мал для математики (ну до 12 лет точно!), либо его успеваемость в школе крайне мала.

Добавлено (08.12.2013, 15:47)
———————————————
Лично я в математике (а следовательно и всех четких науках) силен и благодаря умению хорошо соображать смог научится писать коды еще будучи школотой.

PaRtIzAn_MaXs Дата: Воскресенье, 08 Декабря 2013, 18:50 | Сообщение # 20

почетный гость

Сейчас нет на сайте

Цитата JHawk ()

Лично я в математике (а следовательно и всех четких науках) силен и благодаря умению хорошо соображать смог научится писать коды еще будучи школотой.

У меня по математике 7


C#-Unity3D

  • Страница 1 из 2
  • 1
  • 2
  • »

Question:

Unity doesn’t seem to like the way I’m declaring my variables, I was just trying to clean up my code and moved some of the variables and now it doesn’t work.

The Error:

AssetsMovement.cs(33,22): error CS0029: Cannot implicitly convert type ‘UnityEngine.Vector3’ to ‘float’

AssetsMovement.cs(39,29): error CS1503: Argument 1: cannot convert from ‘float’ to ‘UnityEngine.Vector3’

AssetsMovement.cs(41,29): error CS1503: Argument 1: cannot convert from ‘float’ to ‘UnityEngine.Vector3’

AssetsMovement.cs(43,29): error CS1503: Argument 1: cannot convert from ‘float’ to ‘UnityEngine.Vector3’

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Movement : MonoBehaviour{
    public CharacterController controller;
    public Transform Player;
    public Transform groundCheck;
    public Text StaminaBar;
    public LayerMask groundMask;

    Vector3 move;
    Vector3 velocity;

    float WalkingSpeed = 12;
    float SprintingSpeed = 15;
    float CrouchingSpeed = 6;
    float gravity = 30;

    void Update(){
        Speed();
        Jump();
        Crouching();
        //Gravity
        controller.Move(velocity * Time.deltaTime);
    }
    void Speed(){
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        float CurrentX = Player.transform.position.x;
        float CurrentZ = Player.transform.position.z;
        float move = transform.right * x + transform.forward * z;
        bool isWalking = Input.GetKey(KeyCode.W);
        bool isCrouching = Input.GetKey(KeyCode.LeftShift);
        bool isSprinting = Input.GetKey(KeyCode.R);
        velocity.y += gravity * Time.deltaTime;
        if (isWalking){
            controller.Move(move * WalkingSpeed * Time.deltaTime);
        } else if (isCrouching){
            controller.Move(move * CrouchingSpeed * Time.deltaTime);
        }else if(isSprinting){
            controller.Move(move * SprintingSpeed * Time.deltaTime);
        }
    }
    void Jump(){
        bool isGrounded = Physics.CheckSphere(groundCheck.position, 0.1f, groundMask);
        
    }
    void Crouching(){
    }
    void Sliding(){
    }
    void Climbing(){
    }
    void WallRunning(){
    }
}```

Answer:

You are declaring your variable move multiple times.

float move = ... should be move = ...

If you have better answer, please add a comment about this, thank you!

сохранение

Re: сохранение

вы можете помочь исправить ошибку?? ^:)^ ~x(

Изображение

Аватара пользователя
kolya9898
UNITрон
 
Сообщения: 333
Зарегистрирован: 15 июл 2013, 19:28
Откуда: Челябинск
Skype: kolyan9898

Re: сохранение

Сообщение 2rusbekov 10 фев 2014, 12:21

зачем использовать object[] если можно string[] и коверт во флоат float.Parse(string) и pos должен быть Vector3. в Instantiate.
object name = wordss[ii]; он что должен строку инстанциировать? Скорее надо загрузку префаба с таким именем грузить из Resources
GameObject.FindGameObjectWithTag(«Circle»).transform.position в строке выглядит так «Vector3(1, 1, 1)». и если его присвоить переменной она не станет снова Vector3

Still alive…

Аватара пользователя
2rusbekov
Адепт
 
Сообщения: 1409
Зарегистрирован: 06 апр 2012, 12:57
Откуда: Бишкек

Re: сохранение

Сообщение kolya9898 10 фев 2014, 15:05

2rusbekov писал(а):зачем использовать object[] если можно string[] и коверт во флоат float.Parse(string) и pos должен быть Vector3. в Instantiate.
object name = wordss[ii]; он что должен строку инстанциировать? Скорее надо загрузку префаба с таким именем грузить из Resources
GameObject.FindGameObjectWithTag(«Circle»).transform.position в строке выглядит так «Vector3(1, 1, 1)». и если его присвоить переменной она не станет снова Vector3

Смысле? название префаба Circle(1-2-3-4-5-6-7-8-9-10) -забыл написать Photon.
Дак, а как в юньке сделать чтобы через обычный Instantiate по названию блок респавнить в [RPC]

Изображение

Аватара пользователя
kolya9898
UNITрон
 
Сообщения: 333
Зарегистрирован: 15 июл 2013, 19:28
Откуда: Челябинск
Skype: kolyan9898

Re: сохранение

Сообщение kolya9898 10 фев 2014, 20:44


string[] wordss = wordsl.Split(new string[] { «|» }, StringSplitOptions.RemoveEmptyEntries);
string name = wordss[1/wordss.Length];
string poss = wordss[2/wordss.Length];
Debug.Log (name+»:»+poss);

помогите преобразовать string poss в vector3

Изображение

Аватара пользователя
kolya9898
UNITрон
 
Сообщения: 333
Зарегистрирован: 15 июл 2013, 19:28
Откуда: Челябинск
Skype: kolyan9898

Re: сохранение

Сообщение kolya9898 10 фев 2014, 21:23

help me

Изображение

Аватара пользователя
kolya9898
UNITрон
 
Сообщения: 333
Зарегистрирован: 15 июл 2013, 19:28
Откуда: Челябинск
Skype: kolyan9898


Re: сохранение

Сообщение 2rusbekov 11 фев 2014, 07:48

Всем лень писать такое. Хочешь чтобы написали, плати, за 500 золотых допишу твой код)))

Still alive…

Аватара пользователя
2rusbekov
Адепт
 
Сообщения: 1409
Зарегистрирован: 06 апр 2012, 12:57
Откуда: Бишкек

Re: сохранение

Сообщение kolya9898 11 фев 2014, 11:30

помогите преобразовать string poss в vector3 x_x

Используется csharp

                        Vector3 poss = Convert.ToSingle(wordss[2/wordss.Length]);
 

error CS0029: Cannot implicitly convert type `float’ to `UnityEngine.Vector3′

Изображение

Аватара пользователя
kolya9898
UNITрон
 
Сообщения: 333
Зарегистрирован: 15 июл 2013, 19:28
Откуда: Челябинск
Skype: kolyan9898

Re: сохранение

Сообщение 2rusbekov 11 фев 2014, 11:42

Сохраняй так что ли pos.x + «/» + pos.y + «/» + pos.z
а потом сплит по слешу и new Vectro3(poss[0], poss[1], poss[2]) с преобразованием во флоат

Или подключи жсон библу какую нибудь и не парься.

Still alive…

Аватара пользователя
2rusbekov
Адепт
 
Сообщения: 1409
Зарегистрирован: 06 апр 2012, 12:57
Откуда: Бишкек

Re: сохранение

Сообщение beatlecore 11 фев 2014, 11:45

Вот нашел вам материал для изучения по сериализации, десериализации классов в юнити, соответственно решение вашей проблемы, пишите сразу в бинарник ваши сохранения.

Аватара пользователя
beatlecore
Старожил
 
Сообщения: 964
Зарегистрирован: 05 фев 2013, 21:26
Откуда: Sun Crimea
Skype: beatlecore

загрузка

Сообщение kolya9898 11 фев 2014, 18:35

спасибо большое! (popcorn)

Изображение

Аватара пользователя
kolya9898
UNITрон
 
Сообщения: 333
Зарегистрирован: 15 июл 2013, 19:28
Откуда: Челябинск
Skype: kolyan9898


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: Yandex [Bot] и гости: 22



Shinyo

0 / 0 / 0

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

Сообщений: 6

1

02.06.2020, 18:59. Показов 2107. Ответов 3

Метки rotation, unity2d (Все метки)


Подскажите, как избавиться от ошибки error CS0029: Cannot implicitly convert type ‘UnityEngine.Quaternion’ to ‘UnityEngine.Vector3’ в этом коде

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
class EnemyFollow : MonoBehaviour
{
    GameObject player;
 
    Vector3 p;
 
    const float speedMove = 1.0f;
 
    void Start()
    {
        p = transform.rotation;
        player = GameObject.FindWithTag("Player");
    }
 
    void Update()
    {
        float direction = player.transform.position.x - transform.position.x;
 
        if (Mathf.Abs(direction) < 5)
        {
            Vector3 pos = transform.position;
            pos.x += Mathf.Sign(direction) * speedMove * Time.deltaTime;
            transform.position = pos;
        }
 
        if (p.z == 90)
        {
            this.enabled = false;
        }
    }
}

Добавлено через 30 минут
Забыл добавить, что ошибка на 15 строке

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



0



Эксперт .NET

11075 / 7639 / 1179

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

Сообщений: 28,684

03.06.2020, 06:49

2

Shinyo, должно быть очевидно (из сообщения компилятора), что вы пытаетесь выполнить некорреткное присвоение.



1



3088 / 1617 / 921

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

Сообщений: 4,620

03.06.2020, 08:46

3

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

Решение

p = transform.eulerAngles; наверное.
Но этот код бессмысленный, в данном случае.



1



vk.com/pppoe252110

62 / 43 / 21

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

Сообщений: 251

03.06.2020, 09:42

4

Используйте кватернионы



1



please help, i’m currently working on a brick breaker game and working on paddle script
but it shows error on line 17, i don’t know how to change float to vector3

using UnityEngine;
using System.Collections;

public class Paddle : MonoBehaviour {


    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);

        float mousePosInBlocks = Input.mousePosition / Screen.width * 16;

        paddlePos.x = Mathf.Clamp(mousePosInBlocks, 0.5f, 15.5f);

        this.transform.position = paddlePos;
    }
}

here is the script combined both answers

public class Paddle : MonoBehaviour {

    Vector3 mousePosInBlocks;
    Vector3 paddlePos;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

    paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);

    mousePosInBlocks = Input.mousePosition / Screen.width * 16;

    paddlePos.x = Mathf.Clamp(mousePosInBlocks.x, 0.5f, 15.5f);

    this.transform.position = paddlePos;
}

}

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

Понравилась статья? Поделить с друзьями:
  • Error cs0029 cannot implicitly convert type float to bool
  • Error cs0022 wrong number of indices inside expected 2
  • Error cs0022 wrong number of indexes 2 inside expected 1
  • Error cs0021 cannot apply indexing with to an expression of type image
  • Error cs0019 operator cannot be applied to operands of type vector3 and vector3