Error cs0029 cannot implicitly convert type void to bool

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Diagnostics; using SolidWorks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Diagnostics;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;

namespace ClassLibrary1
{
    public class Class1
    {
        public void open_swfile(string filepath, int x, string pgid)
        {
            SldWorks swApp = null;
            ModelDoc2 swAssemModleDoc = null;
            //SldWorks swApp;

            if (x == 0)
            {
                MessageBox.Show("no SolidWorks");
            }
            else if (x == 1)
            {
                System.Type swtype = System.Type.GetTypeFromProgID(pgid);
                swApp = (SldWorks)System.Activator.CreateInstance(swtype);
                //swApp.Visible = true;
                swAssemModleDoc = (ModelDoc2)swApp.ActiveDoc;
            }
        }

        public static void ProcessExited()
        {
            Process[] processes = Process.GetProcessesByName("SLDWORKS");

            foreach (Process process in processes)
            {
                if (process.ProcessName == "SLDWORKS")
                {
                    return true;
                }
            }

            return false;
        }

        public static void DoKillOnce()
        {
            Process[] processes = Process.GetProcessesByName("SLDWORKS");

            foreach (Process process in processes)
            {
                if (process.ProcessName == "SLDWORKS")
                {
                    try
                    {
                        process.Kill();
                    }
                    catch
                    {
                    }
                }
            }
        }

        public static void KILLSW()
        {
            if (ProcessExited())
            {
                do
                {
                    DoKillOnce();
                } while (ProcessExited());
                MessageBox.Show("Soldiworks process clean!");
            }
            else
            {
                MessageBox.Show("no process!");
            }
        }
    }
}

Getting errors:

CS0103 The name ‘MessageBox’ does not exist in the current context ClassLibrary2 23 Active
Error CS0127 Since ‘Class1.ProcessExited()’ returns void, a return keyword must not be followed by an object expression ClassLibrary2 40 Active
Error CS0127 Since ‘Class1.ProcessExited()’ returns void, a return keyword must not be followed by an object expression ClassLibrary2 43 Active
Error CS0029 Cannot implicitly convert type ‘void’ to ‘bool’ ClassLibrary2 65 Active
Error CS0029 Cannot implicitly convert type ‘void’ to ‘bool’ ClassLibrary2 70 Active
Error CS0103 The name ‘MessageBox’ does not exist in the current context ClassLibrary2 71 Active
Error CS0103 The name ‘MessageBox’ does not exist in the current context ClassLibrary2 75 Active

Warning NU1701 using“.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8”not“.NETStandard,Version=v2.1”Restore package“SolidWorks.Interop 16.10.0”。This package may not be fully compatible with the project. ClassLibrary2 1

marc_s's user avatar

marc_s

722k173 gold badges1320 silver badges1443 bronze badges

asked Feb 8, 2020 at 17:39

sunne's user avatar

1

void isn’t a type, more the absence of a type.

It means that a method doesn’t return a value. You are trying to return a value (true or false in this case) from a method that is declared as returning no value.

You have to specify a return type on the method if you want to return a type

public static bool ProcessExited() 
{
  return true;
}

answered Feb 8, 2020 at 17:41

Kurt Hamilton's user avatar

Kurt HamiltonKurt Hamilton

12.3k1 gold badge21 silver badges36 bronze badges

Make the following corrections:

CS0103 The name ‘MessageBox’ does not exist in the current context
ClassLibrary2 23 Active

  • Right Click Project > Add > Reference > Assemblies > System.Windows.Forms

Error CS0127 Since ‘Class1.ProcessExited()’ returns void, a return
keyword must not be followed by an object expression ClassLibrary2 43
Active

  • Change return type of ProcessExited() from Void to bool

Note

You can use inbuilt property Process.HasExited to check the associated process has been terminated.

 if (process.HasExited==true)
 {
   //This process has exited, do something 
 } 

answered Feb 8, 2020 at 17:46

Clint's user avatar

ClintClint

5,7811 gold badge20 silver badges28 bronze badges

2

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
  • Remove From My Forums
  • Вопрос

  • Hi, as you can see I messed up my display name lol. 

    To the question:

    Here’s what I’m trying to do:

     case 725010:
                  {
                    if (Character.LearnSkill(1046, 4, 0))
                    {
    
                    }
                    else
                    {
    
                    }
    
                    break;
                  }

    Here is the definition:

    public void LearnSkill(int SkillID, int Level, int EXP)
        {
    
          if (Skills.ContainsKey(SkillID))
          {
            Skill TheSkill = Skills[SkillID];
            TheSkill.SkillEXP = EXP;
            TheSkill.SkillID = SkillID;
            TheSkill.SkillLevel = Level;
          }
          else
          {
            Skill TheSkill = new Skill();
            TheSkill.SkillEXP = EXP;
            TheSkill.SkillID = SkillID;
            TheSkill.SkillLevel = Level;
    
            Skills.Add(SkillID, TheSkill);
          }
        }

    I don’t know what to do.  I’ve been at it for 3 hours.

    Thanks for any help, I really do appreciate it.

Ответы

  • if (Character.LearnSkill(1046, 4, 0))

    The line above is expecting a boolean true or false value, however the method is not returning anything. It is marked as ‘void’. To use the line above you need to change the method it calls to return a boolean something like the following….

    public bool LearnSkill(int SkillID, int Level, int EXP)
    
     {
    
    
    
      if (Skills.ContainsKey(SkillID))
    
      {
    
      Skill TheSkill = Skills[SkillID];
    
      TheSkill.SkillEXP = EXP;
    
      TheSkill.SkillID = SkillID;
    
      TheSkill.SkillLevel = Level;
    
      return true;
    
      }
    
      else
    
      {
    
      Skill TheSkill = new Skill();
    
      TheSkill.SkillEXP = EXP;
    
      TheSkill.SkillID = SkillID;
    
      TheSkill.SkillLevel = Level;
    
    
    
      Skills.Add(SkillID, TheSkill);
    
      return false;
    
      }
    
     }

    • Предложено в качестве ответа

      17 мая 2011 г. 15:45

    • Помечено в качестве ответа
      lucy-liuModerator
      25 мая 2011 г. 6:33

Why is this bit of code:

    protected bool IsServerPeer(InitRequest initRequest)
    {
        return _subServerCollection.IsServerPeer(initRequest);
    }

creating the error:

Cannot implicitly convert type ‘void’ to ‘bool’


Probably because _subServerCollection.IsServerPeer() has the return type void

Related Articles

Can not implicitly convert SqlBoolean type to bool, or can you?

Consider the following lines of code: System.Data.SqlTypes.SqlBoolean sb = true; // (1) bool b = sb; // (2) bool b = sb ? true : false; // (3) if (sb) // (4) { } (1) works fine, I guess because of public static implicit operator SqlBoolean(bool x). (

Can not implicitly convert ‘void’ type to ‘System.Threading.Tasks.Task’

Here is simplified version of my code below which is generating following compilation error Cannot implicitly convert type ‘void’ to ‘System.Threading.Tasks.Task’ GetDataAsync method does not need to return anything in this case. How can I make it re

CS0029 Error: Can not Implicitly Convert Int Type to Bool ‘- Unity3D

I got error CS0029: Cannot implicitly convert type int to bool error. Here’s my code : using UnityEngine; using System.Collections; public class card2 : MonoBehaviour { public GUISkin MenuSkin; public int cardinpuani; public float sekiz = 8; public f

Can not implicitly convert the type of Task & lt; & gt;

I am trying to master async method syntax in .NET 4.5. I thought I had understood the examples exactly however no matter what the type of the async method is (ie Task<T>), I always get the same type of error error on the conversion back to T — which

can not implicitly convert the type ‘bool?’ to ‘bool’. An explicit conversion exists (is there a distribution missing?)

Error : cannot implicitly convert type ‘bool?’ to ‘bool’. An explicit conversion exists (are you missing a cast?) Code : Test obj = new Test(); obj.IsDisplay = chkDisplay.IsChecked; but when i use this means cast in bool then there is no error. Test

can not implicitly convert the type ‘int’ to ‘bool’ and I do not understand

This question already has an answer here: Cannot implicitly convert type ‘int’ to ‘bool’ [duplicate] 5 answers I’m trying to create a brick breaker type game with a ball and bat. I’m working on making the ball reflect off the bat like it does with th

& Ldquo; Can not implicitly convert the type ‘System.Collections.Generic.IEnumerable’ C3S.Models.Permission & gt; ‘ To ‘bool’. & Rdquo;

I’m trying to code a Home screen so that a given user sees Menu Options depending on their Permissions. Basically, going through each Menu Option, seeing what permissions are need to see it, and then checking to see if the current user has any of tho

Can not implicitly convert ‘void’ to ‘int’?

Oke so I am fairly new to programming and I don’t get why I get this error. My method should store mails which it does in this method: public void StoreMail(PhishingMail PhishingMail) { using (var phishingMailStorage = new PhishFinderModel()) { phish

Can not implicitly convert DbSet type

I have a context that contains many DbSets. Some of these DbSets implement an interface called IActivity which contains a number of common fields such as TimeReceived, TimeSent. In my controller, I need to read values from one of the context DbSets b

ASP.NET C # & ldquo; can not implicitly convert the type ‘string’ to ‘int’ & rdquo; Error

OK, so I’m using Mono on Mac OS X to work simple «applications» using ASP.NET and C# and I’m having two issues with my code. Here is my Default.aspx presentation markup: <%@ Page Language=»C#» Inherits=»project1.Tree» %>

Can not implicitly convert the type ‘System.Collections.Generic.List’ String & gt; ‘ To ‘System.Collections.Generic.IEnumerable’ Turon.Model.Products_Products & gt;

public IEnumerable<Products_Products> getprod() { var db = new Model.atengturonDBEntities(); IEnumerable<Products_Products> x = new List<Products_Products>(); var test = (from name in db.Products_Products select name.ProductName).ToList(

can not implicitly convert the type ‘System.Linq.IQueryable’ to ‘System.Linq.IQueryable’

I’m working on a project where I’m trying to use entity framework to provide data to a WCF service. The code follows: public IQueryable<vwTP90Web> GetTP90() { TP90Entities context = new TP90Entities(); var tp90web = (from p in context.vw_TP90Web sel

can not implicitly convert the type to a group

I get this error when i try to groupby CellID. Cannot implicitly convert type ‘System.Collections.Generic.List System.Linq.IGrouping int,p2pControllerLogAnalyser.Models.GSMData’ to ‘System.Collections.Generic.List p2pControllerLogAnalyser.Models.GSMD

can not implicitly convert the type System.DateTime? at System.DateTime

When I do the following I get: inv.RSV = pid.RSVDate I get the following: cannot implicitly convert type System.DateTime? to System.DateTime. In this case, inv.RSV is DateTime and pid.RSVDate is DateTime? I tried the following but was not successful:

Here, have a look: Unity — Scripting API: Physics.Raycast[^]
Physics.Raycast returns a boolean type. You have assigned that to variable of type RaycastHit and thus the error.

It straight away returns true if the ray intersects with a Collider, otherwise false.

Thus,

void Shoot()
{
  if (Physics.Raycast(firePoint.position, firePoint.right))
  {
    
  }
}

Go through some documentation and article to learn about it, like:
How to Create a Raycast in Unity 3D | Studica Blog[^]

UPDATE:
A sample for you

void FixedUpdate()
    {
        
        int layerMask = 1 << 8;

        
        
        layerMask = ~layerMask;

        RaycastHit hit;
        
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
            Debug.Log("Did Hit");
        }
        else
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
            Debug.Log("Did not Hit");
        }
    }

Reference: Unity — Scripting API: Physics.Raycast[^]

Suggestion: Please go through the link above and examples there instead of trying to follow some youtube. Until you understand basics and how to use IDE, it would be difficult for you to follow.

error CS0029. Как так???

nanaminer Дата: Вторник, 16 Мая 2017, 12:50 | Сообщение # 1

частый гость

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

Здравствуйте!
У меня есть ассет PuppetMaster, я хочу обратится к одному из скриптов, но Unity не понимает, тип переменной из скрипта к которому я хочу обратиться и пишет мне:
error CS0029: Cannot implicitly convert type `int’ to `RootMotion.Dynamics.Weight’ crazy т.е. Unity не понимает, что Puppet.GetComponent<BehaviourPuppet> ().collisionResistance это int. Как объяснить это Unity?
Помогите пожалуйста, Зарание спасибо!
Вот мой код:

Код

using UnityEngine;
using System.Collections;
using RootMotion.Dynamics;
using RootMotion;
using RootMotion.Demos;

public class Puppet : MonoBehaviour {

public GameObject Puppet;

void Start(){
Puppet.GetComponent<BehaviourPuppet> ().collisionResistance = 0;
}
}

Vostrugin Дата: Вторник, 16 Мая 2017, 14:01 | Сообщение # 2

постоянный участник

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

Судя по всему это Вы не понимаете, а не Unity. Поле collisionResistance имеет тип Weight, о чём и говорит ошибка.




EchoIT Дата: Вторник, 16 Мая 2017, 18:23 | Сообщение # 3

старожил

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

nanaminer, ты сейчас берёшь и удаляешь все ассеты, затем выкачиваешь справку по C# и Unity Scripting API на комп, а затем на месяц себе отрубаешь интернет, и работаешь, используя только эту информацию. Исключительно только после этого можешь продолжать заниматься геймдевом.


Долгожданный анонсик: State of War

nanaminer Дата: Среда, 17 Мая 2017, 14:09 | Сообщение # 4

частый гость

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

Здравствуйте, спасибо за отклик.

Небольшая выдержка из скрипта к которому я обращаюсь:

Код

[TooltipAttribute(«Smaller value means more unpinning from collisions (multiplier).»)]
   /// <summary>
   /// Smaller value means more unpinning from collisions (multiplier).
   /// </summary>
   public float collisionResistance;

Т.е. эта переменная float.
(как float я тоже пытался обращаться — та-же ошибка)
Как так? %)

Storm54 Дата: Четверг, 18 Мая 2017, 09:56 | Сообщение # 5

постоянный участник

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

Вроде ошибка совсем в другом месте. Например, класса RootMotion я не вижу
nanaminer Дата: Пятница, 19 Мая 2017, 18:26 | Сообщение # 6

частый гость

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

Здравствуйте.

Цитата Storm54 ()

класса RootMotion я не вижу

Не видите где? В скрипте с объявлением переменной только выдержка, весь скрипт огромный, но там есть этот класс.

seaman Дата: Пятница, 19 Мая 2017, 22:55 | Сообщение # 7

старожил

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

Может Вы все же ошиблись строкой где выдает ошибку? Приведите сообщение об ошибке полностью, чтоб была указана строка и кусок кода с этой строкой.
Может ошибка рядом? Например — зачем Вам включать все эти скрипты?

Код

using RootMotion.Dynamics;
using RootMotion;
using RootMotion.Demos;

Может достаточно одного RootMotion? Может у них (хотя конечно маловероятно) повторяются определения в разных namespace?

nanaminer Дата: Понедельник, 22 Мая 2017, 14:50 | Сообщение # 8

частый гость

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

Здравствуйте!
Спасибо всем, кто помогал, сегодня нашёл решение:

Код

Puppet.GetComponent<BehaviourPuppet> ().collisionResistance.floatValue = 0;

нужно было добавить, что изменяю именно floatValue ^_^ .

seaman Дата: Понедельник, 22 Мая 2017, 18:08 | Сообщение # 9

старожил

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

Тогда от чего же вы писали:

Цитата

public float collisionResistance;
Т.е. эта переменная float.

Вводили нас в заблуждение?
Вам с самого начала говорили, что «Поле collisionResistance имеет тип Weight»

Сообщение отредактировал seamanПонедельник, 22 Мая 2017, 18:08

Asked
2 years, 10 months ago

Viewed
1k times

$begingroup$

I have a problem with pressing UI button while cursor is locked. I tried to write in the script so that the cursor unlocks when a button appears on the screen, but the error «Cannot implicitly convert type «void» to «bool»» appeared. I searched for a solution on the Internet, but none of the solutions I found helped me.

public GameObject button;

// Use this for initialization
void Start () {
    LockCursor();
}

// Update is called once per frame
void Update () {
    if(Input.GetKeyDown(KeyCode.Escape))
    {
        UnlockCursor();
    }

    if(Input.GetMouseButton(0))
    {
        LockCursor();
    }

    if(button.SetActive(true))
    {
        UnlockCursor();
    }
}

private void LockCursor()
{
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

private void UnlockCursor()
{
    Cursor.lockState = CursorLockMode.None;
    Cursor.visible = true;
}

What can I do to solve this issue?
Thanks for any help!

asked Mar 21, 2020 at 14:50

Hyperka 's user avatar

$endgroup$

2

$begingroup$

I have found a solution. In this case, the «.activeSelf» function is required. This function checks if the object is active or not and returns local active state of the GameObject.

answered Mar 21, 2020 at 15:30

Hyperka 's user avatar

Hyperka Hyperka

331 silver badge10 bronze badges

$endgroup$

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Понравилась статья? Поделить с друзьями:
  • 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