Error cs0030 cannot convert type string to int

User-1467402001 posted
  • Remove From My Forums
  • Question

  • User-1467402001 posted

    I wrote the follwing code to Insert data in SQL Server in two tables. What i have done is I inserted Username password in one table then i got the Max vale of Id field which is of Numeric type.  i  

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.IO;

    public partial class register : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void submitcv_Click(object sender, ImageClickEventArgs e)
    {
    Int32 Maxid;
    SqlConnection conn = new SqlConnection("Server=(local);Database=career;Trusted_Connection=yes;");
    SqlCommand com1 = new SqlCommand("Insert Into Seeker_Authen Values('"+usernametxt.Text+"','"+passwordtxt.Text+"','"+DateTime.Now+"')",conn);
    SqlCommand com2 = new SqlCommand("select Max(Seeker_id) from Seeker_Authen",conn);
    SqlDataReader dr;
    try { conn.Open(); com1.ExecuteNonQuery(); dr = com2.ExecuteReader(); while (dr.Read())
    {
    Response.Write("i'm in");
    Maxid = (int)(dr[0].GetType().ToString());
    Response.Write(Maxid);
    }
    string cv_url = Server.MapPath("upload")+uploadfile.FileName;
    Response.Write(cv_url);
    SqlCommand Com3 = new SqlCommand("Insert into Seeker_Details values(" + Maxid + ",'" + firstname.Text + "','" + lastname.Text + "','" + gender.SelectedItem.Value+ "','" + address.Text + "','" + city.Text + "','" + country.Text + "','" + visa.SelectedItem.Value + "','" + landphone.Text + "','" + mobile.Text + "','" + func_area.Text + "','" + experience.Text + "','" +skills.Text + "','" + cv_url + "')", conn);
    Com3.ExecuteNonQuery();

    }
    catch { Response.Write("Failed to add at First stage");
    }

    }
    }

     tried to sotre it in a int Variable it show this error

Answers

  • User1001868398 posted

    Changed this line  

     Maxid = (int)(dr[0].GetType().ToString());

    To

    Maxid = Int32.Parse(dr[0].ToString());

    Hope this helps

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User-531099263 posted

    I think it should be:

    while (dr.Read())
    {
           Response.Write(«i’m in»);
            Maxid =
    dr[0].GetInt32; 
            Response.Write(Maxid);
     } 

    Burl

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

  • User-417784260 posted

     Use ExecuteScalar if you are trying to return 1 value from a database

     string sMax = cmd2.ExecuteScalar().ToString();

                if (Int32.TryParse(sMax,out MaxID))
                {
                    // You have a valid number
                }
                else
                {
                    // You did not get a number back
                }

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

  • User187056398 posted

    Try this:

    Maxid = (int)dr[0];   

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

  • User1835558127 posted
    use int.parse(yours datareader statement)

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

Hi I have a data on my web I want to run the RSS FEED the subject above is the Compiler Error Message CS0030 Cannot convert type string to int Kindly help


Hi,

you need to implicitly convert an string to an int as here:

string strNumber = "123";
int nTest = 0;
Int32.TryParse(strNumber, out nTest);

Updated 19-Jan-11 22:43pm

int intA=Convert.ToInt32("string");

Use this code this will be very simple to convert a string into an Integer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

Your sample code

int i;
i += textBox1.Text;
textBox1.Text = i;

has some problems.

First, you’ll get a compiler error (two, actually) due to the type mismatch. i is an int; textBox.Textis a string. There is no implicit cast or conversion fromstringtoint` and so the compiler throws an error.

Second, having fixed the above issue, you’ll get another compiler error due to i not being initialized. The C# specification required variable to be explicitly assigned a value prior to first use. Something like i += j; is shorthand for i = i + j;. And since you haven’t assigned a value to i, the compiler throws an error.

You might note that the compiler errors you see

error CS0030: Cannot convert type 'string' to 'int'
error CS0029: Cannot implicitly convert type 'string' to 'int'

and

error CS0165: Use of unassigned local variable 'i'

are rather descriptive of the problem. The solution should be rather obvious on reading the compiler error messages. What you want to do is something like:

int value ;
bool parsed = int.TryParse(textBox1.Text,out value ) ;

if ( !parsed ) throw new InvalidOperationException( "you should have client-side validators on textBox1") ;

i += value ;

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

maxkoshevoi opened this issue

Feb 19, 2021

· 27 comments

Comments

@maxkoshevoi

I’m creating an analyzer (https://github.com/dotnet/roslyn-analyzers/issues/4479) that reports if foreach will perform explicit cast in runtime (which is likely result in runtime exception):

image

This issue is to ask approval to set RuleLevel for that analyzer as BuildWarning.

  • If explicit cast is not intended, user should definitely be warned about potential runtime exception
  • If explicit cast is intended, user should do it explicitly, so that intent is clear.

@dotnet-issue-labeler

I couldn’t figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

@stephentoub

This issue is to ask approval to set RuleLevel for that analyzer as BuildWarning.

If I changed your highlighted example to:

List<object> x = new List<object>() { "hello" };
foreach (string s in x) { ... }

is that going to warn? If yes, I don’t think we should have this analyzer at all, nevermind what its default warning level is. It’s going to be incredibly noisy, I fear. If we do add it, it should at most be info by default. The statement «If explicit cast is intended, user should do it explicitly, so that intent is clear» highlights that this is really a rule about style.
cc: @mavasani

@maxkoshevoi



Copy link


Contributor

Author

is that going to warn?

It will be reported for your example. Default (and current) RuleLevel is IdeSuggestion.

The statement «If explicit cast is intended, user should do it explicitly, so that intent is clear» highlights that this is really a rule about style

That’s fair. To be honest, If it would be possible to not report explicit conversion that would succeed in runtime, I would’ve implemented that analyzer so it doesn’t report them. But only runtime can tell that (we can receive that collection from some third-party code, for example).

Main goal of this analyzer is to warn about InvalidCastException in runtime. So successful casts can be considered as some kind of false positive. I agree with your point, that since it reports them, it shouldn’t be a warning.

What do you think about leaving it as suggestion?

It’s going to be incredibly noisy, I fear

I thought, usually foreach iterator variable has following types:

  • var
  • Exact collection item type (or its base type)
  • Interface that collection item type implements

For all of those cases this analyzer wouldn’t be reported since implicit cast is used there.

This analyzer will only be reported if foreach will attempt to cast

  • From base class to child class
  • From interface to class that implements it

I don’t think those cases are common (at least I didn’t encounter them)

Also, this unobvious explicit cast is already forbidden for tuples:
image

@stephentoub

I don’t think those cases are common (at least I didn’t encounter them)

They’re very common, especially when working with non-generic collection types. I tried the rule from your PR on dotnet/runtime, and it yielded 1199 warnings; I sampled them, and none of the ones I looked at were bugs.

I don’t think we should be adding this rule, or if others really think it’s impactful, it should default to a level of None.

@maxkoshevoi



Copy link


Contributor

Author

especially when working with non-generic collection types

Thanks for the insight! Want’s aware that non-generic collections are still so widely used.
What if we limit the scope of this analyzer to only types that implement IEnumerable<T>?

@mavasani

I tend to agree with @stephentoub. Given the high false positive rate, this rule if approved, should most likely be a disabled by default rule OR silent/hidden so it’s a refactoring.

@stephentoub

@maxkoshevoi



Copy link


Contributor

Author

Won’t the existing compiler CS0030 error catch the majority of such misuse?

This analyzer reports only is cast doesn’t exist (even explicit one).

Proposed analyzer is targeted at cases where foreach will try to cast base class to it child (explicit cast exists, so CS0030 wouldn’t be reported).

It’s not only about object collections. Here are two examples:

var x = new List<IComparable>() { 5 };
foreach (string s in x)
{
}
var x = new List<A>() { new() };
foreach (B item in x)
{
}

class A { }
class B : A { }

Side note: We can even exclude object collection from this analyzer as well. So it will only look at types that implement IEnumerabe<T> where T is not object. That should greatly reduce number of cases where analyzer interferes with developers intent.

@stephentoub

Proposed analyzer is targeted at cases where foreach will try to cast base class to it child

Right. I’m saying that such use is the minority, and when it does exist, the developer is using the foreach as a way to write the cast. In your example, if someone has:

var x = new List<IComparable>() { "hello" };
foreach (string s in x)
{
}

your rule is going to warn, but this is perfectly valid, and either they’re going to be forced to suppress the rule or change their code to the less concise / less readable:

var x = new List<IComparable>() { "hello" };
foreach (IComparable i in x)
{
    string s = (string)i;
}

I don’t see the benefit.

@maxkoshevoi



Copy link


Contributor

Author

I’m saying that such use is the minority

Intentional use. Such code might be written by mistake.
I come up with the idea for analyzer when I refactored a collection type to its base type in one place, and code crashed in runtime on a foreach loop that used that collection. I forgot to change variable type there and VS didn’t notify me that I forgot that.

I don’t see the benefit.

My thinking was that explicit cast needs to be done explicitly. If I don’t want to use explicit cast, and using foreach as a regular loop, VS should notify me somehow (warning or suggestion) that explicit cast will be performed here in runtime.

@stephentoub

Such code might be written by mistake.

So, why not write a rule that flags every explicit cast from a base type to a derived type? Maybe the developer made a mistake.

That’s essentially what this rule is proposing doing. (And obviously we’re not going to add such a rule :)

@maxkoshevoi



Copy link


Contributor

Author

flags every explicit cast from a base type to a derived type

Is .Net compiler generates such cast somewhere else except when compiling foreach?
I mean, if user has written cast manually (B)a, it’s obviously doesn’t need to be flagged. User clearly expressed an intent to perform an explicit cast. When using foreach you don’t express this intent.

Usually .Net asks to perform cast explicitly when user tries to assign variable of base type to a derived type.
B b = a

Or even here:
image

@stephentoub

I mean, if user has written such manually (B)a, it’s obviously doesn’t need to be flagged

I don’t see the difference. The developer is saying «given this collection, I would like to enumerate every element in it, referring to each as an xyz». Whether they write it as foreach (xyz item in collection) { ... } or foreach (object o in collection) { xyz item = (xyz)o; }, they’re saying the same thing. I think your objection is to this behavior of foreach, but that’s how foreach has always worked. And I don’t see how the latter form is any more explicit or intentional than the former form. You described refactoring a loop and accidentally not changing the foreach and getting an exception at runtime; such an issue is no less likely to happen if you’d written it with an explicit cast.

@maxkoshevoi



Copy link


Contributor

Author

such an issue is no less likely to happen if you’d written it with an explicit cast

Exactly. But I didn’t want to do any casting, I just wanted to enumerate the elements. Variable type was there only for code readability (so I don’t need to hover over var to see what type it is).
If I’d done the same refactoring, but got a runtime exception on a cast, I wouldn’t be surprised. Explicit cast is explicit exactly because is can fail.

given this collection, I would like to enumerate every element in it, referring to each as an xyz

Yes, that was my thinking too. I thought that this:

var x = new List<IComparable>();
foreach (string s in x)
{
}

Is equivalent to this:

var x = new List<IComparable>();
for (int i = 0; i < x.Count; i++)
{
    string s = x[i];
}

But compiler will report a CS0266 for second code snippet, but not for the first. I understand that this was done because foreach was created when generics didn’t exists, and it would be tedious to cast from object manually every time, but now we have generics.

I’m trying to make it behave the same for both cases.

We can even exclude all object collections from this analyzer as well. So it will only look at types that implement IEnumerabe<T> where T is not object.

@stephentoub

I understand that this was done because foreach was created when generics didn’t exists, and it would be tedious to cast from object manually every time, but now we have generics.

I don’t believe analyzers we ship in the SDK are a place to retcon behaviors of the C# language.

@maxkoshevoi



Copy link


Contributor

Author

@stephentoub as you said, this rule shouldn’t be a warning (or an error), and compiler doesn’t generate suggestions, only analyzer does (if I’m not mistaken).

It would be a suggestion that notifies about existing C# behavior, that might not be obvious (like CA2246 does, for example).

No one will change this behavior of foreach since it would break a lot of code bases, but it least non-breaking analyzer for it would be nice.

@jmarolf

If there is case where we can know that something is always a runtime error then I agree that it is an excellent case for a potential analyzer. Unfortunately, I don’t see how this analyzer can ever be definitive in its recommendations.

As @stephentoub says the compiler already warns for cases that we know will cause runtime failures:

using System;
using System.Collections.Generic;

public class C {
    public void M() {
        var list = new List<string>() { "Hello World" };
        foreach (int i in list) // error CS0030: Cannot convert type 'string' to 'int'
        {
            Console.WriteLine(i);
        }
    }
}

My understanding of what is being proposed is that we now warn for this case as well:

using System;
using System.Collections.Generic;

public class C {
    public void M() {
        var list = new List<object>() { "Hello World" };
        foreach (int i in list) // New warning about casting object to int
        {
            Console.WriteLine(i);
        }
    }
}

I can understand the implicit cast in foreach can be surprising but that’s how the language works. Whenever you see foreach (int value in list) you should think for (int i = 0, value = 0; i < list.Count; value=(int)list[i], i++). If you do not want that to happen you can use var which will type the value as whatever it actually is instead of attempting to cast it.

You could require this pattern in your codebase so all casts are explicit:

using System;
using System.Collections.Generic;

public class C {
    public void M() {
        var list = new List<object>() { "Hello World" };
        foreach (var value in list) 
        {
            int i = (int)value;
        }
    }
}

Or this:

using System;
using System.Collections.Generic;
using System.Linq;

public class C {
    public void M() {
        var list = new List<object>() { "Hello World" };
        foreach (var i in list.Cast<int>()) 
        {
            
        }
    }
}

But this really becomes a style argument about what the best way to express to readers that you intend the cast that is happening.

@GrabYourPitchforks

Is there a guide somewhere to the philosophy of analyzers? I can see correctness-style analyzers falling under three general categories.

  1. The code you’ve written is going to fail at runtime. Don’t even bother hitting F5. (See existing error code CS0030.)
  2. The code you’ve written may succeed at runtime or it mail fail at runtime. Practically speaking, it will always* go down the «success» path or it will always go down the «failure» path, but we can’t really tell from static analysis which world we’re in. If you hit F5 you’ll find out quickly which side you’re on.
  3. The code you’ve written may succeed or fail at runtime, but it will do so non-deterministically, or the variables which affect success vs. failure may be environment-dependent and very difficult to reason about. Your production server might observe different behaviors than your test server.

My opinion (and just my opinion) is that these are also in increasing order of importance for an analyzer to flag. [3] is the most important because it’s alerting you to a problem that you might not even know about until your prod server falls over unexpectedly. [1] and [2] are less important. We should flag them if we can, but if we miss something it’s not the end of the world, as the developer will immediately see any runtime failure as soon as they exercise this code path.

For [2], I’d rather err on the side of false negatives instead of false positives. Other posters in this thread described their concerns behind a false positive rate. On the other hand, the worst consequence of a false negative is that you see the failure the first time you run your app, and you spend a minute or two debugging it. That doesn’t seem all that bad, to be honest.

* I’m using «always» a bit liberally. That is, if your test cases all populate the List<object> with strings, and you assume this is representative of a typical scenario, then you «always» go down the success path for typical inputs. And if you happen to receive an atypical input, your implicit cast acts as a quasi Debug.Assert("I really expected this to be a string and haven't tested this code for other data types."). Score one for invariant checking! :)

@maxkoshevoi



Copy link


Contributor

Author

You could require this pattern in your codebase so all casts are explicit
But this really becomes a style argument about what the best way to express to readers that you intend the cast that is happening.

@jmarolf Hm, great point, I’m actually more concerned about style here, then whether code will fail it runtime or not. My point is that all explicit casts (from parent to child, or from interface to class that implements it) should be explicitly written. This would serve two goals:

  • Confirms the intent that user didn’t make a mistake in foreach variable type and indeed wants to perform such cast
  • Shows someone how reads the code, this it can fail here. Yes, maybe people should be aware that foreach always does cast under the hood, but it’s used so frequently to just iterate collections that when reading the code I don’t assume that any foreach is a potential runtime error. Right now It requires some research to determine if some particular foreach performs explicit cast or not.

I’m not proposing that all foreach statements look like this from now on:

foreach (var item in list.Cast<T>()) 
{            
}

Only once that will actually perform explicit cast (from parent to child, or from interface to class that implements it) in runtime.

@GrabYourPitchforks This analyzer falls into 2 and 3 category (we don’t know where collection came from, and how it’s values are populated), but mostly 2, I think.

Regarding false positives, @stephentoub helped identify two groups so far:

  • object collections (like ArrayList). A lot of code is already written for them and it expects foreach to cast them to some type, so there shouldn’t be any surprise that it performs explicit cast in their case. I excluded such collections from this analyzer, so this is no longer a false positive.
    I’m not sure if generic collections with object as type argument (List<object>) should be included in this bucket though. Would like to hear any thoughts on this.
  • Collections that always return one type. For example:
    foreach (string item in GenerateSequence())
    {
    }
    
    IEnumerable<IComparable> GenerateSequence()
    {
    }

    Here’s an example from dotnet/runtime. Here explicit cast is performed since Instantiation returns TypeDesc and GenericParameterDesc is derived from TypeDesc. Should it be flagged with this analyzer to manually perform the cast? Also would like to hear any thoughts on this. Here is another example (schema.Includes is XmlSchemaObject)

As for other false positives, I didn’t find any so far (at least in dotnet/runtime nothing is flagged if I exclude everything mentioned above). I’ll try to scan other repositories to see if there are some other cases that potentially need to be marked as false positive.

@stephentoub

I do appreciate all the effort here, but let’s not add this to roslyn-analyzers. The concern here is about style, and it would be better suited to an analyzer suite focused on style, e.g. stylecop.

@maxkoshevoi



Copy link


Contributor

Author

If the concern is about style, it would be better suited to an analyzer suite focused on style, e.g. stylecop.

This style safeguards users from potential runtime issues (like CA2245 or CA2248, for example), it’s not only about code readability.
Can we include it as suggestion if all mentioned false positives are excluded?

@AraHaan

I would prefer this rule to be in stylecop as it fits more into style.

Besides it warns when people use objects, now there is a chance that for cases like ISomeInterfaceHere upcasting to a class that implements said interface might not be a bug at all.

However it would be nice if foreach did have a way to pattern match instead of casting (like from ISomeInterfaceHere to MyClassIneheritingFromSomeInterfaceHere) instead of the cast.

However there is another issue:

  • what if code that would not be using foreach pattern matching gets falsely detected as a pattern match by the compiler.
  • other issues.

And yes the only places I can see foreach pattern matching of any use are:

  • loading types from 1 assembly using reflection (after loading them using AppDomains or AssemblyLoadContexts)
  • base classes -> implementing ones.
  • etc.

However I do think pattern matching foreach would be great to add to avoid implicit casting inside of them (and makes the intent more clearer if one did not want to use var).

However in my code even on my own Plugin Loaders, using AppDomain or not, uses var on everything just because I prefer var for everything unless I explicitly cannot use var for something.

Also another note one can also do this if upcasting is intended as well too:

foreach (var something in somethings)
{
    // use pattern matching to determine the real types of the type of 'something'
    // (Interface or whatever) and do things based on whatever the type really is.
}

@stephentoub

safeguards users from potential runtime issues

I don’t believe it does.

@jmarolf

safeguards users from potential runtime issues

This same argument could be made for warning about all explicit casts. The developer may be new to C# and be unaware that the cast will cause runtime errors. My understanding of the problem as it happened is:

start with code like this

List<Student> People {get;}

// some levels of object-oriented layering later...

foreach(Student student in People)
{
	...
}

We then add a base type like say Person that Student inherits from and update our collection to contain the base type

List<Person> People {get;}

// some levels of object-oriented layering later...

foreach(Student student in People)
{
	...
}

the compiler doesn’t warn because this cast could succeed. There may even be paths were nothing happens and ones where there is a runtime exception. While I am sympathetic, I do not see a universal way to address this problem today. If I am an analyzer, the developer needs to communicate to me what their intent is. There are millions of lines of code that do this today and I shouldn’t warn them just because there exists some situations where this could be non-intentional.

If, in my codebase, this sort of refactoring is happening all the time I would personally use var in a lot of places. I might even recommend var be used everywhere. That was one of the reasons var became so common in the IDE codebase of roslyn, because we kept refactoring different layers and we didn’t want to deal with the fallout of updating thousands of variable declaration locations.

However, these sorts of refactors never happen at the compiler layer. For that reason the roslyn compiler layer does not use var at all.

This is the reason the style rules for https://github.com/dotnet/roslyn are what they are and why I think this analysis is best expressed in something like stylecop.

@maxkoshevoi



Copy link


Contributor

Author

@stephentoub

@jmarolf

Is there a guide somewhere to the philosophy of analyzers? I can see correctness-style analyzers falling under three general categories.

  1. The code you’ve written is going to fail at runtime. Don’t even bother hitting F5. (See existing error code CS0030.)
  2. The code you’ve written may succeed at runtime or it mail fail at runtime. Practically speaking, it will always* go down the «success» path or it will always go down the «failure» path, but we can’t really tell from static analysis which world we’re in. If you hit F5 you’ll find out quickly which side you’re on.
  3. The code you’ve written may succeed or fail at runtime, but it will do so non-deterministically, or the variables which affect success vs. failure may be environment-dependent and very difficult to reason about. Your production server might observe different behaviors than your test server.

Interestingly I do see things a little differently. For cases like [1] I am annoyed as a developer if the tooling could have told me something was wrong sooner but «wasted my time» by assuming I would figure it out eventually. In general, false positives are extremely detrimental to analysis being successful. If warnings are only sometimes correct it’s just another cognitive load on the developer. Now in addition to whatever they have on their plate they need to take the time to reason about all these diagnostics and decide if they are false positives. The urge to just silence all warnings goes up for every false positive that it encountered. I see these as being in priority order:

  1. The code will compile and run without error, but will silently not do what you want (like CA2247 or passing async void delegates to something that takes an Action). roslyn#12649 is the most extreme example I can think of. These are the obvious slam dunks and should be on by default. Some of these will even come directly from the compiler instead of analyzers.
  2. The code will fail at runtime 100% of the time. Also an obvious analyzer candidate as it makes my tools smarter and the amount of time I spend figuring out what went wrong is reduced. This is the category all the platform analyzers fall into for me.
  3. The code you’ve written may succeed at runtime or it may fail at runtime. CA2015 is in this category. Here the question is «What is the probability if will fail at runtime vs. succeed?» AND «How many codebases have this pattern in them already?». This is the central metric I think we need to apply for everything after [0] and [1]. In the case of CA2015 there is a 99% chance the code will fail and do something horrific with a slim chance that it will be fine «just for debugging». It is also likely there are only a handful of codebases on earth that need to implement the MemoryManager<T> type.

Applying these principled to the rule proposed in this issue:

  • What are the chances the code succeeds (What is the false positive rate)?
    • This issue will only present in code that hasn’t run, so newly written or modified code. Because of this it seems unlikely that any analysis warnings that appear in existing foreach loops will contain actual bugs. By this metric I would expect every single warning that appears in the dotnet/runtime repo to be a false positive. Again, because this issue is likely to appear in newly written or newly changed code and foreach loops are used a lot.
  • How many code bases already have this pattern
    • Hard to say but everything we know says that var usage in foreach is about 50/50
    • foreach (var is used ~150K on github so lets say ~150K don’t use var in foreach. Thats a lot of code that is has been running for years without issue and would potentially be flagged.

Because this has a potential for a high false positive rate in a large number of codebases I think its a non-starter.

@msftbot
msftbot
bot

locked as resolved and limited conversation to collaborators

Mar 23, 2021

  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /

avatar image


0

i would like to now if there is a way to convert t$$anonymous$$s code

 GetComponent(GUIText).text = parseInt(Time.time).ToString();

USING C#

Do t$$anonymous$$s right.?

 GetComponent<GUIText>().text=int.Parse(Time.time.ToString());

Cast the float (time.time); a = time.time int b = (int) a then b.ToString

 GetComponent<GUIText>().text = Time.time.ToString();


Time.time is a float, not an int.

2 Replies

·
Add your reply

  • Sort: 

avatar image


0

Answer by Matthew012 · Aug 29, 2013 at 11:16 PM

Just do t$$anonymous$$s.

GetComponent(GUIText).text = Time.time.ToString();

or use ToString(#) to format the output to a simple number, depending on OPs needs

right!

But I want use my timer

I just want to integer

my error is CS0030: Cannot convert type string’ to int’

avatar image


0

Answer by sourna · Sep 02, 2013 at 08:55 PM

$$anonymous$$ii

i fiiiiiiind

fiiiiind

:D

Time.time is double

code C# is :

 using UnityEngine;
 using System.Collections;
 
 public class Timer : MonoBehaviour {
     //float startTimer=Time.time;
     // Use t$$anonymous$$s for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         double a=Time.time;
         int b;
         b= (int)a;
         GetComponent<GUIText>().text=b.ToString ();
     
     }
 }
 

Your answer

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.

Follow this Question

Related Questions

Rachel Soderberg

Most of the time Visual Studio is pretty good about telling us where syntax errors and other bugs are hiding. Occasionally though (even after our tech lead has warned us to be on the lookout for «that one bug» they mentioned) even the best of us get stumped. Some of the most challenging bugs can be run time errors — especially the ones that are hiding deep within the code base, don’t cause any Intellisense warnings or errors, and aren’t developer-caused. In the case of the CS0030 error, it happens in a generated file in which you’re warned «Changes to this file may cause incorrect behavior».

When I ran across this issue, it dawned on me after perhaps a little too long that my tech lead’s infamous «double bracket bug» was exactly what was I was ramming my head against when I added our Salesforce web reference to my project. It also dawned on me that others may have the same hangup as me and that I should write about it to share. I’m not going to get overly technical in this article; my main goal is to get problem and resolution across in a written format.

Now to the problem! For whatever reason, when some web references are added, Visual Studio decides to be extra doubly helpful when generating the reference class files and builds something like this:

https://thepracticaldev.s3.amazonaws.com/i/6v7l84azs423j9ec3ood.PNG

(Note the double pairs of brackets, one of which I highlighted. That highlighted one shouldn’t be there.)

Once you’ve run across this a time or two, it’s like second nature to fix it, but for those who are in their first CS0030 rodeo I wanted to share how I found and resolved the issue:

  • First I checked StackOverflow and found a lot of good info here regarding why it happens to XmlElementAttribute, and that it’s not really that uncommon: https://stackoverflow.com/questions/6678934/unable-to-generate-a-temporary-class-result-1-error-cs0030-cannot-convert-ty
  • Second I went to my Salesforce web reference class file and searched for ‘[][]’. Lo and behold, about 255k lines in, there was a pair of a pair of brackets! Deleting one of the two pairs resolved the issue, allowing me to continue on my merry way to running and testing through my code.

In summary, if you have recently added one or several web references to your C# project and Visual Studio gives you an error code of CS0030 take a look at their reference classes and search for double brackets ‘[][]’. You may just have an extra pair or two hiding in there.

www_024

0 / 0 / 0

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

Сообщений: 2

1

16.11.2021, 13:39. Показов 2953. Ответов 2

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


Проблема в CS0030 Не удается преобразовать тип «System.Collections.Generic.List<string>» в «string»133 строка
в функции savevalues

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
namespace EXAM_11._11
{
    class MyDict
    {
        public string type { get; set; }
        private Dictionary<string, List<string>> data;
 
        public MyDict()
        {
            this.type = "Unknown";
            this.data = new Dictionary<string, List<string>>();
        }
        public MyDict(string type)
        {
            this.type = type;
            this.data = new Dictionary<string, List<string>>();
        }
        /// <summary>
        /// Добавить новое слово в словарь
        /// </summary>
        /// <param name="key">Слово</param>
        /// <param name="word">Значение слова</param>
        public void append(string key, string word)
        {
            key = key.ToLower(); // SfdSfsD --> sfdsfsd
            if (data.ContainsKey(key)){
                List<string> values = data[key];
                values.Add(word);
                data[key] = values;
            } else
            {
                List<string> values = new List<string> { word };
                data.Add(key, values);
            }
            
        }
 
        /// <summary>
        /// Поиск значений слова
        /// </summary>
        /// <param name="key">Ключ</param>
        /// <returns></returns>
        public List<string> search(string key)
        {
            key = key.ToLower();
            List<string> res = new List<string>();
            if (data.ContainsKey(key))
            {
                res = new List<string>(data[key]);
            }
            return res;
        }
 
        public void replace_key(string oldKey, string newKey)
        {
            newKey = newKey.ToLower();
            oldKey = oldKey.ToLower();
            if (data.ContainsKey(oldKey))
            {
                List<string> newValues = new List<string>(data[oldKey]);
                data.Add(newKey, newValues);
                data.Remove(oldKey);
 
            }
           
        }
 
        public void replace_value(string key, string value, int index)
        {
            key = key.ToLower();
            if (data.ContainsKey(key))
            {
                if (data[key].Count() > index && index >= 0)
                {
                    data[key][index] = value;
                }
            }
        }
 
        public override string ToString()
        {
            string text = $"Тип словаря:{this.type}";
            foreach (string key in data.Keys)
            {
                string newKey = key;
                newKey = newKey.Remove(0, 1);
                newKey = key.ToUpper()[0] + newKey;
                text += $"n{newKey}:";
                int index = 1;
                foreach(string value in data[key])
                {
                    text += $" {index++}.{value};";
                }
            }
            return text;
        }
        public void savetype()
        {
            string text = $"Тип словаря:{this.type}";
            string save = @"E:text.txt";
            using (FileStream fstream = new FileStream($"{save}", FileMode.OpenOrCreate))
            {
                byte[] array = System.Text.Encoding.Default.GetBytes(text);
                fstream.Write(array, 0, array.Length);
                Console.WriteLine("Тип словаря записан в файл");
            }
        }
        public void savekey(string values)
        {
            foreach (string key in data.Keys)
            {
                values = key;
            }
          
            string save = @"E:text.txt";
            MyDict dictsave = new MyDict(save);
            using (FileStream fstream = new FileStream($"{save}", FileMode.OpenOrCreate))
            {
                byte[] array = System.Text.Encoding.Default.GetBytes(values);
                fstream.Write(array, 0, array.Length);
                Console.WriteLine("Слово записано в файл");
            }
        }
        public void savevalues(string input)
        {
            foreach (string values in data.Values)
            {
                input = values;
            }
            string save = @"E:text.txt";
            MyDict dictsave = new MyDict(save);
            using (FileStream fstream = new FileStream($"{save}", FileMode.OpenOrCreate))
            {
                byte[] array = System.Text.Encoding.Default.GetBytes(input);
                fstream.Write(array, 0, array.Length);
                Console.WriteLine("Значение записано в файл");
            }
        }
        public void readingfile()
        {
            string save = @"E:rus-eng.txt";
            using (FileStream fstream = File.OpenRead($"{save}"))
            {
                byte[] array = new byte[fstream.Length];
                fstream.Read(array, 0, array.Length);
                string textFromFile = System.Text.Encoding.Default.GetString(array);
                Console.WriteLine($"Тип вашего словаря: {textFromFile}");
            }
        }
    }
}

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



0



AndreyVorobey

2656 / 1591 / 850

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

Сообщений: 5,494

16.11.2021, 15:29

2

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

Решение

www_024, а код Ваш вообще?
какие-то странные вопросы возникают. ну логично, ведь в стравочнике значение имеет тип List, а Вы пихаете в строку.

C#
1
2
3
4
            foreach (var row in data.Values)
            {
                 input += String.Join(", ", row) + Environment.NewLine;
            }



1



Luca Brasi

881 / 193 / 53

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

Сообщений: 1,916

Записей в блоге: 2

16.11.2021, 16:21

3

www_024,

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
   public void savevalues(string input)
        {
            foreach (string values in data.Values)
            {
                input = values;
            }
            string save = @"E:text.txt";
            MyDict dictsave = new MyDict(save);
            using (FileStream fstream = new FileStream($"{save}", FileMode.OpenOrCreate))
            {
                byte[] array = System.Text.Encoding.Default.GetBytes(input);
                fstream.Write(array, 0, array.Length);
                Console.WriteLine("Значение записано в файл");
            }
        }

а это что вообще? Зачем передавать инпут, если данные беруться из поля data? Я понимаю, input был бы еще внешним типом, но он тут как-то вообще бесполезен…
Ну и да, определитесь что собираетесь итерировать в коде возникшей ошибки, а то там словарь.



0



Avatar of mlong219

mlong219

Flag for United States of America asked on 5/4/2011

Two questions….

1. How do I convert this to a int/whole number, in C#?
2. How do I truncate the .0 on the end? Anything to the right of the decimal I want removed?

sValue = «0.0»;

Thanks.

C#

Avatar of undefined

Last Comment

Mike Tomlinson


8/22/2022 — Mon

int num = (int) 0.0;
// num = 0

 
int num2 = (int)12.2434234;
 // num2 = 12

@RajkumarGS:

I just tried this and I get the error: CS0030: Cannot convert type ‘string’ to ‘int’

int iTotalReports = (int) sTotalReports;

I have a string variable with a value of «0.0», that I need to convert to int, and also get rid of the decimal place.

I got it working by doing the following….

string sTotalReports = «0.0»;
int iTotalReports = Convert.ToInt32(Convert.ToDecimal(sTotalReports));

I would think there is a better way.

You can use Math.Floor function

     string strTax = "23.67";
        decimal decTax = Math.Floor(Convert.ToDecimal( strTax));
        // Result = 23

Open in new window

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.

View this solution by signing up for a free trial.

Members can start a

7-Day free trial

and enjoy unlimited access to the platform.

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.

View this solution by signing up for a free trial.

Members can start a

7-Day free trial

and enjoy unlimited access to the platform.

Obadiah Christopher

5/4/2011

Isn’t there something called abs in C#? Or it shd be Math.Abs. Not sure if anything like this exists.

There is…but Math.Abs() just gives you the absolute value of a number (not the integral part).

error CS0030: Cannot convert type `string’ to `int’ .
Или это не эксепшен а вовсе синтаксическая ошибка? впрочем int — valuetype, a string — referencetype, но строки в int ведь превращаються?🧐

Но int.Parse(«string») ловит? как FormatException
я думал try catch всеядная..

russian

programming

dot


2

ответов

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

String ссылочный тип, а int структура, структура не лежит в иерархии наследования string, поэтому явное приведение невозможно, поэтому ты получаешь ошибку еще на этапе компиляции. try catch работает позже, на этапе выполнения, до которого ты не дойдешь с этим кодом. Если охото проверить try catch приведи строку к object, а т.к. все унаследовано от него — можно попробовать object явно привести к int — тогда сработает catch.

Похожие вопросы

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