Implicit conversion from number to string как исправить

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

Введение

При использовании новой версии компилятора языка MQL4 некоторые старые программы могут выдавать ошибки.

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

Новый компилятор позволяет обнаружить реальные или потенциальные источники ошибок и повысить качество кода.

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

  1. Ошибки компиляции
    • 1.1. Идентификатор совпадает с зарезервированным словом
    • 1.2. Специальные символы в наименованиях переменных и функций
    • 1.3. Ошибки использования оператора switch
    • 1.4. Возвращаемые значения у функций
    • 1.5. Массивы в аргументах функций
  2. Ошибки времени выполнения
    • 2.1. Выход за пределы массива (Array out of range)
    • 2.2. Деление на ноль (Zero divide)
    • 2.3. Использование 0 вместо NULL для текущего символа
    • 2.4. Строки в формате Unicodе и их использование в DLL
    • 2.5. Совместное использование файлов
    • 2.6. Особенность преобразования datetime
  3. Предупреждения компилятора
    • 3.1. Пересечения имен глобальных и локальных переменных
    • 3.2. Несоответствие типов
    • 3.3. Неиспользуемые переменные

1. Ошибки компиляции

При наличии ошибок в коде программа не может быть скомпилирована.

Для полного контроля всех ошибок рекомендуется использовать строгий режим компиляции, который устанавливается директивой:

#property strict

Этот режим значительно упрощает поиск ошибок.

1.1. Идентификатор совпадает с зарезервированным словом

Если наименование переменной или функции совпадает с одним из зарезервированных слов:

int char[];  
int char1[]; 
int char()   
{
 return(0);
}

то компилятор выводит сообщения об ошибках:

Рис.1. Ошибки "unexpected token" и "name expected"

Рис.1. Ошибки «unexpected token» и «name expected»

Для исправления данной ошибки нужно исправить имя переменной или функции.

1.2. Специальные символы в наименованиях переменных и функций

Если наименования переменных или функций содержат специальные символы ($, @, точка):

int $var1; 
int @var2; 
int var.3; 
void f@()  
{
 return;
}

то компилятор выводит сообщения об ошибках:

Рис.2. Ошибки "unknown symbol" и "semicolon expected"

Рис.2. Ошибки «unknown symbol» и «semicolon expected»

Для исправления данной ошибки нужно скорректировать имена переменных или функций.

1.3. Ошибки использования оператора switch

Старая версия компилятора позволяла использовать любые значения в выражениях и константах оператора switch:

void start()
  {
   double n=3.14;
   switch(n)
     {
      case 3.14: Print("Pi");break;
      case 2.7: Print("E");break;
     }
  }

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

Рис.3. Ошибки "illegal switch expression type" и "constant expression is not integral"

Рис.3. Ошибки «illegal switch expression type» и «constant expression is not integral»

В таких случаях можно использовать явные сравнения численных значений, например:

void start()
  {
   double n=3.14;
   if(n==3.14) Print("Pi");
   else
      if(n==2.7) Print("E");
  }

1.4. Возвращаемые значений функций

Все функции, кроме void, должны возвращать значение объявленного типа. Например:

int function()
{
}

При строгом режиме компиляции (strict) возникает ошибка:

Рис.4. Ошибка "not all control paths return a value"

Рис.4. Ошибка «not all control paths return a value»

В режиме компиляции по умолчанию компилятор выводит предупреждение:

Рис.5. Предупреждение "not all control paths return a value"

Рис.5. Предупреждение «not all control paths return a value»

Если возвращаемое значение функции не соответствует объявлению:

int init()                         
  {
   return;                          
  }

то при строгом режиме компиляции возникает ошибка:

Рис.6. Ошибка "function must return a value"

Рис.6. Ошибка «function must return a value»

В режиме компиляции по умолчанию компилятор выводит предупреждение:

Рис.7. Предупреждение 'return - function must return a value"

Рис.7. Предупреждение ‘return — function must return a value»

Для исправления таких ошибок в код функции нужно добавить оператор возврата return c возвращаемым значением соответствующего типа.

1.5. Массивы в аргументах функций

Массивы в аргументах функций теперь передаются только по ссылке.

double ArrayAverage(double a[])
{
 return(0);
}

Данный код при строгом режиме компиляции (strict) приведет к ошибке:

Рис.8. Ошибка компилятора "arrays passed by reference only"

Рис.8. Ошибка компилятора «arrays passed by reference only»

В режиме компиляции по умолчанию компилятор выводит предупреждение:

Рис.9. Предупреждение компилятора "arrays passed by reference only"

Рис.9. Предупреждение компилятора «arrays passed by reference only»

Для исправления таких ошибок нужно явно указать передачу массива по ссылке, добавив префикс & перед именем массива:

double ArrayAverage(double &a[])
{
 return(0);
}

Следует отметить, что теперь константные массивы (Time[], Open[], High[], Low[], Close[], Volume[]) не могут быть переданы по ссылке. Например, вызов:

ArrayAverage(Open);

вне зависимости от режима компиляции приводит к ошибке:

Рис.10. Ошибка 'Open' - constant variable cannot be passed as reference

Рис.10. Ошибка ‘Open’ — constant variable cannot be passed as reference

Для устранения подобных ошибок нужно скопировать необходимые данные из константного массива:

   
   double OpenPrices[];
   
   ArrayCopy(OpenPrices,Open,0,0,WHOLE_ARRAY);
   
   ArrayAverage(OpenPrices);

2. Ошибки времени выполнения

Ошибки, возникающие в процессе исполнения кода программы принято называть ошибками времени выполнения (runtime errors). Такие ошибки обычно зависят от состояния программы и связаны с некорректными значениями переменных.

Например, если переменная используется в качестве индекса элементов массива, то ее отрицательные значения неизбежно приведут к выходу за пределы массива.

2.1. Выход за пределы массива (Array out of range)

Эта ошибка часто возникает в индикаторах при обращении к индикаторным буферам. Функция IndicatorCounted() возвращает количество баров, неизменившихся после последнего вызова индикатора. Значения индикаторов на уже рассчитанных ранее
барах не нуждаются в пересчете, поэтому для ускорения расчетов
достаточно обрабатывать только несколько последних баров.

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



int start()
  {
   
   if (Bars<100) 
     return(-1); 

   
   int counted_bars=IndicatorCounted();
   
   if(counted_bars<0) return(-1);
      
   
   int limit=Bars-counted_bars;

   
   if(counted_bars==0) 
     {
      limit--;  
      
      limit-=10;
     }
   else 
     {     
      
      limit++;
     } 
   
   for (int i=limit; i>0; i--)
   {
     Buff1[i]=0.5*(Open[i+5]+Close[i+10]) 
   }
}

Часто встречается некорректная обработка случая counted_bars==0 (начальную позицию limit нужно уменьшить на значение, равное 1 + максимальный индекс относительно переменной цикла).

Также следует помнить о том, что в момент исполнения функции start() мы можем обращаться к элементам массивов индикаторных буферов от 0 до Bars()-1. Если есть необходимость работы с массивами, которые не являются индикаторными буферами, то их размер следует увеличить при помощи функции ArrayResize() в соответствии с текущим размером индикаторных буферов. Максимальный индекс элемента для адресации также можно получить вызовом ArraySize() с одним из индикаторных буферов в качестве аргумента.

2.2. Деление на ноль (Zero divide)

Ошибка «Zero divide» возникает в случае, если при выполнении операции деления делитель оказывается равен нулю:

void OnStart()
  {

   int a=0, b=0,c;
   c=a/b;
   Print("c=",c);
  }

При выполнении данного скрипта во вкладке «Эксперты» возникает сообщение об ошибке и завершении работы программы:

Рис.11. Сообщение об ошибке "zero divide"

Рис.11. Сообщение об ошибке «zero divide»

Обычно такая ошибка возникает в случаях, когда значение делителя определяется значениями каких-либо внешних данных. Например, если анализируются параметры торговли, то величина задействованной маржи оказывается равна 0 если нет открытых ордеров. Другой пример: если анализируемые данные считываются из файла, то в случае его отсутствия нельзя гарантировать корректную работу. По этой причине желательно стараться учитывать подобные случаи и корректно их обрабатывать.

Самый простой способ — проверять делитель перед операцией деления и выводить сообщение об некорректном значении параметра:

void OnStart()
  {

   int a=0, b=0,c;
   if(b!=0) {c=a/b; Print(c);}
   else {Print("Error: b=0"); return; };
  }

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

Рис. 12. Сообщение о некорректном значении делителя

Рис. 12. Сообщение о некорректном значении делителя

2.3. Использование 0 вместо NULL для текущего символа

В старой версии компилятора допускалось использование 0 (нуля) в качестве аргумента в функциях, требующих указания финансового инструмента.

Например, значение технического индикатора Moving Average для текущего символа можно было запрашивать следующим образом:

AlligatorJawsBuffer[i]=iMA(0,0,13,8,MODE_SMMA,PRICE_MEDIAN,i); 

В новом компиляторе для указания текущего символа нужно явно указывать NULL:

AlligatorJawsBuffer[i]=iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i); 

Кроме того, текущий символ и период графика можно указать при помощи функций Symbol() и Period().

AlligatorJawsBuffer[i]=iMA(Symbol(),Period(),13,8,MODE_SMMA,PRICE_MEDIAN,i); 

2.4. Строки в формате Unicodе и их использование в DLL

Строки теперь представляют собой последовательность символов Unicode.

Следует учитывать этот факт и использовать соответствующие функции Windows. Например, при использовании функций библиотеки wininet.dll вместо InternetOpenA() и InternetOpenUrlA() следует вызывать InternetOpenW() и InternetOpenUrlW().

В MQL4 изменилась внутренняя структура строк (теперь она занимает 12 байт), поэтому при передаче строк в DLL следует использовать структуру MqlString:

#pragma pack(push,1)
struct MqlString
  {
   int      size;       
   LPWSTR   buffer;     
   int      reserved;   
  };
#pragma pack(pop,1)

2.5. Совместное использование файлов

В новом MQL4 при открытии файлов необходимо явно указывать флаги FILE_SHARE_WRITE и FILE_SHARE_READ для совместного использования.

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

Например, при работе с оффлайновыми графиками требуется явно указывать флаги совместного доступа:

   
   ExtHandle=FileOpenHistory(c_symbol+i_period+".hst",FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ);

Подробности можно найти в статье в статье «Оффлайновые графики и новый MQL4«.

2.6. Особенность преобразования datetime

Следует иметь ввиду, что преобразование типа datetime в строку теперь зависит от режима компиляции:

  datetime date=D'2014.03.05 15:46:58';
  string str="mydate="+date;

Например, попытка работы с файлами, имя которых содержит двоеточие, приведет к ошибке.

3. Предупреждения компилятора

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

Чистый код не должен содержать предупреждений.

3.1. Пересечения имен глобальных и локальных переменных

Если на глобальном и локальном уровнях присутствуют переменные с одинаковыми именами:

int i; 
void OnStart()
  {

   int i=0,j=0; 
   for (i=0; i<5; i++) {j+=i;}
   PrintFormat("i=%d, j=%d",i,j);
  }

то компилятор выводит предупреждение и укажет номер строки, на которой объявлена глобальная переменная:

Рис.13. Предупреждение "declaration of '%' hides global declaration at line %"

Рис.13. Предупреждение «declaration of ‘%’ hides global declaration at line %»

Для исправления таких предупреждений нужно скорректировать имена глобальных переменных.

3.2. Несоответствие типов

В новой версии компилятора введена операция приведения типов.

#property strict
void OnStart()
  {
   double a=7;
   float b=a;
   int c=b;
   string str=c;
   Print(c);
  }

В строгом режиме компиляции при несоответствии типов компилятор выводит предупреждения:

Рис.14. Предупреждения "possible loss of data due to type conversion" и "implicit conversion from 'number' to 'string'

Рис.14. Предупреждения «possible loss of data due to type conversion» и «implicit conversion from ‘number’ to ‘string’

В данном примере компилятор предупреждает о возможной потере точности при присвоении различных типов данных и неявном преобразовании типа int в string.

Для исправления нужно использовать явное приведение типов:

#property strict
void OnStart()
  {
   double a=7;
   float b=(float)a;
   int c=(int)b;
   string str=(string)c;
   Print(c);
  }

3.3. Неиспользуемые переменные

Наличие переменных, которые не используются в коде программы (лишние сущности) не является хорошим тоном.

void OnStart()
  {
   int i,j=10,k,l,m,n2=1;
   for(i=0; i<5; i++) {j+=i;}
  }

Сообщения о таких переменных выводятся вне зависимости от режима компиляции:

Рис.15. Предупреждения "variable '%' not used'

Рис.15. Предупреждения «variable ‘%’ not used’

Для исправления нужно убрать неиспользуемые переменные из кода программы.

Выводы

В статье рассмотрены типичные проблемы, с которыми могут столкнуться программисты при компиляции старых программ, содержащих ошибки.

Во всех случаях при отладке программ рекомендуется использовать строгий режим компиляции.

Предупреждение: все права на данные материалы принадлежат MetaQuotes Ltd. Полная или частичная перепечатка запрещена.

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

Steviey opened this issue

Jan 13, 2019

· 5 comments


Closed

[RESOLVED] Implicit Conversion Warnings

#10

Steviey opened this issue

Jan 13, 2019

· 5 comments

Assignees

@integracore2

Comments

@Steviey

DWX_ZeroMQ_Server_v2.0.1_RC8

I get a bunch of warnings…actually can’t been overseen…

implicit conversion from ‘number’ to ‘string’ (multiple lines)
declaration of ‘data’ hides global declaration in file […] Z85.mqh (multiple lines)
expression not boolean GlobalVariable.mqh (multiple lines)

By the way, is this server version for Python only?
I can’t find any information, on how to handle the versions in regard to R.
And is it OK to use the old version because of its simple, easy to extend structur?

Thank you.

@TimKabue

Hello Steviey,
The «implicit conversion from ‘number’ to ‘string'» is brought about in mql4 when you convert a number variable to a string variable in your code without explicitly coding it to do that. For example:

int number = 10;
Alert(number);

The above code will throw that warning. Instead, you should convert the the variable ‘number’ of type integer to type string. Like this:

int number = 10;
Alert(string(number));

Use the function string(); to remove those errors.

@TimKabue

@integracore2

Hi @Steviey ,

Thank you for raising this — could you please do the following:

  1. paste a text log of the warnings generated? need to ascertain which files are generating them, the MQL4 script for the EA itself, the dependencies, and/or both.

  2. confirm which version / which file you are referencing here in this issue?

The latest MQL4 EA in v2.0.1_RC8 is language-neutral in the sense that you can implement the sequence of commands and send to the EA via any programming language of choice.

As long as the message is structured as the EA is expecting it in, the sending application could be any ZeroMQ supported language capable of digesting JSON responses.

We have not yet released a version for v2.0.1_RC8 in R, only Python.

Thanks!

@integracore2

[UPDATE] Implicit conversion warnings resolved in an updated DWX_ZeroMQ_Server_v2.0.1_RC8.mq4.

Changes will be committed shortly.

@integracore2
integracore2

changed the title
Bunch of Warnings

[RESOLVED] Bunch of Warnings

Jan 15, 2019

@integracore2

@integracore2
integracore2

changed the title
[RESOLVED] Bunch of Warnings

[RESOLVED] Implicit Conversion Warnings

Jan 15, 2019

На чтение 5 мин. Просмотров 103 Опубликовано 15.12.2019

Я делаю эту простую операцию со строкой в VB.NET

У меня есть строка информации, называемая segmentInfo выглядит так:

Поэтому я просто пытаюсь получить номер из него:

И я получаю на самом деле 2 предупреждения. Оба предупреждения указаны в одной строке кода.

Может быть, я мог понять первый, о string integer . но второй? Я не понимаю.

В любом случае, может кто-нибудь сказать мне, что я делаю неправильно и как это исправить?

string vb.net warnings implicit-conversion

Содержание

  1. 4 ответа
  2. 4 Answers 4
  3. Описание
  4. 1. Названия переменных с вспомогательными символами например . (точка)
  5. 2. Задекларированных переменных теперь больше, и переменные, которые были названы именами новых функций — требует изменения имени.
  6. 3. Каждая функция теперь должна иметь оператор возврата RETURN
  7. 4. Функция switсh в качестве выражения может принимать только Целые числа
  8. 5. Все переменные объявленные внутри функции, должны отличаться от названий глобальных переменных (Необязательно)
  9. 6. Все переменные, должны соответствовать по типу в используемых функциях
  10. 7. Сторонние библиотеки и функции , которые включают в себя передачу строк в DLL
  11. 8. Жесткий поиск ошибок #property strict
  12. 9. Все остальные ошибки и предупреждения решаются в индивидуальном порядке.
  13. 10. Еще один нюанс в 625 билде терминала мт4 should be checked
  14. 11. check operator precedence for possible error; use parentheses to clarify precedence

4 ответа

2 Решение Nico Schertler [2015-07-01 09:44:00]

Метод Split принимает Char (массив) как параметр, а не строку. Следовательно:

Во-вторых, вам нужно проанализировать полученную строку на целое число:

Сделайте это только тогда, когда вы знаете, что строка — это число. В противном случае используйте TryParse .

I currently have a generic class which allows the use of an expression as the value.

What I would like to be able to do is to set properties using implicit conversions from both T and from string. However if the expression is of type string, the compiler cannot decide which conversion to use.

Is there a clever way around this?

4 Answers 4

You won’t be able to keep both implicit operators and expect to work with an Expression because of the better conversion rule

Given an implicit conversion C1 that converts from a type S to a type T1, and an implicit conversion C2 that converts from a type S to a type T2, the better conversion of the two conversions is determined as follows:

  • If T1 and T2 are the same type, neither conversion is better.
  • If S is T1, C1 is the better conversion.
  • If S is T2, C2 is the better conversion.
  • If an implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists, C1 is the better conversion.
  • If an implicit conversion from T2 to T1 exists, and no implicit conversion from T1 to T2 exists, C2 is the better conversion.
  • If T1 is sbyte and T2 is byte, ushort, uint, or ulong, C1 is the better conversion.
  • If T2 is sbyte and T1 is byte, ushort, uint, or ulong, C2 is the better conversion.
  • If T1 is short and T2 is ushort, uint, or ulong, C1 is the better conversion.
  • If T2 is short and T1 is ushort, uint, or ulong, C2 is the better conversion.
  • If T1 is int and T2 is uint, or ulong, C1 is the better conversion.
  • If T2 is int and T1 is uint, or ulong, C2 is the better conversion.
  • If T1 is long and T2 is ulong, C1 is the better conversion.
  • If T2 is long and T1 is ulong, C2 is the better conversion.
  • Otherwise, neither conversion is better.

If an implicit conversion C1 is defined by these rules to be a better conversion than an implicit conversion C2, then it is also the case that C2 is a worse conversion than C1.

With an Expression you are clearly in the first case, the compiler won’t choose for you and will just stop there.

If there is not exactly one function member that is better than all other function members, then the function member invocation is ambiguous and a compile-time error occurs.

So you won’t be able to handle with with conversion operators only; either create additional methods to deal with string explicitly, convert the string to T outside of the operator or create a wrapping abstraction that would be able to tranport T, a string representation of T or the ExpressionText value and convert from it.

Описание

Новый язык программирования терминала МТ4 стал очень богатым. Он существенно расширил свои границы, здесь появились классы, ООП, графические элементы, новые операции с счетом, новые функции. Но и проблем с старым кодом здесь также присутствует.

1. Названия переменных с вспомогательными символами например . (точка)

2. Задекларированных переменных теперь больше, и переменные, которые были названы именами новых функций — требует изменения имени.

3. Каждая функция теперь должна иметь оператор возврата RETURN

4. Функция switсh в качестве выражения может принимать только Целые числа

5. Все переменные объявленные внутри функции, должны отличаться от названий глобальных переменных (Необязательно)

6. Все переменные, должны соответствовать по типу в используемых функциях

7. Сторонние библиотеки и функции , которые включают в себя передачу строк в DLL

8. Жесткий поиск ошибок #property strict

9. Все остальные ошибки и предупреждения решаются в индивидуальном порядке.

10. Еще один нюанс в 625 билде терминала мт4 should be checked

  • return value of ‘OrderSelect’ should be checked
  • return value of ‘OrderDelete’ should be checked
  • return value of ‘OrderSend’ should be checked
  • return value of ‘OrderClose’ should be checked
  • return value of ‘OrderModify’ should be checked

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

  • bool select1=OrderSelect.
  • bool delete1= OrderDelete .
  • bool close1= OrderClose .
  • bool modify1= OrderModify .
  • int send1= OrderSend .

11. check operator precedence for possible error; use parentheses to clarify precedence

предупреждения касаются очередности операторов иили

например у Вас написано:

то предупреждение пропадет.

Т.е. если у Вас в условии написано и и и или или или , без скобок,

не хватает скобок, их нужно расставить правильно.

в декомпилированном коде это не совсем удобно, потому что от скобки зависит торговля всего эксперта.

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • VS 2012 [RESOLVED]implicit conversion from integer to string

  1. May 17th, 2013, 11:04 PM


    #1

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Resolved [RESOLVED]implicit conversion from integer to string

    Reviewing some code that says

    Code:

    TextBox14.Text = GetSettingInt("TMaxUPSpeed")

    Being new to programming, can someone explain to me in the most basic format what exactly this means, what does implicit conversion mean and implicit conversion from integer to string mean, what is it trying to tell me here?

    The code is some sample code I am using to be part of a larger app and the code is also from 2009 which shouldnt really make a difference.

    Thank you

    ** Going to Resolve this post, seems to be an open ended debate on the question, I have already sorted the question out, I paid someone to fix the issue instead, I was a tad frustrated by some of the posts, but thanks to all that replied, moving onto other issues.

    Last edited by jokerfool; May 24th, 2013 at 12:59 AM.

    Reason: Too many people complaining


  2. May 17th, 2013, 11:15 PM


    #2

    Re: implicit conversion from integer to string

    Quote Originally Posted by jokerfool
    View Post

    Reviewing some code that says

    Code:

    TextBox14.Text = GetSettingInt("TMaxUPSpeed")

    Being new to programming, can someone explain to me in the most basic format what exactly this means, what does implicit conversion mean and implicit conversion from integer to string mean, what is it trying to tell me here?

    The code is some sample code I am using to be part of a larger app and the code is also from 2009 which shouldnt really make a difference.

    Thank you

    We cant help with the above code as we do not know what GetSettingInt is. None the less its asking for an integer value. Your parsing a string value.

    String «The Quick Brown Fox…»
    Integer 8 etc..


  3. May 17th, 2013, 11:48 PM


    #3

    Re: implicit conversion from integer to string

    An implicit conversion occurs when you assign a value of one data type to a variable of a different, incompatible data type. For instance, this code implicitly converts a String to an Integer:

    Code:

    Dim int As Integer = "100"

    The value «100» is a String and the ‘int’ variable can only hold and Integer, so the system has to implicitly convert the String to an Integer and then assign the result to the variable. This code performs an explicitly conversion:

    Code:

    Dim int As Integer = CInt("100")

    CInt explicitly converts the String to an Integer and then assign the result to the variable. In that case the code tells the system exactly what to do rather than assuming that the system will work it out for itself.

    In your case, presumably the GetSettingInt method returns an Integer while the Text property of a TextBox (in fact, of any control) is type String. You need to explicitly convert the Integer to a String before assigning it to a String property:

    Code:

    TextBox14.Text = GetSettingInt("TMaxUPSpeed").ToString()


  4. May 18th, 2013, 12:05 AM


    #4

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    Looking for the GetSettingInt here is the function I think for that

    Code:

    Function GetSettingInt(ByVal name As String) As Integer
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
                Return CInt(File.ReadAllText(subdirName & "s." & name & ".n"))
            Else
                Return Nothing
            End If
        End Function


  5. May 18th, 2013, 06:12 AM


    #5

    Re: implicit conversion from integer to string

    Quote Originally Posted by jokerfool
    View Post

    Looking for the GetSettingInt here is the function I think for that

    Code:

    Function GetSettingInt(ByVal name As String) As Integer
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
                Return CInt(File.ReadAllText(subdirName & "s." & name & ".n"))
            Else
                Return Nothing
            End If
        End Function

    ReadAllText returns a string value. Why are you casting this as an integer?

    http://msdn.microsoft.com/en-us/library/ms143368.aspx

    vb Code:

    1. Public Class Form1

    2.     Function GetSettingInt(ByVal name As String) As String

    3.         Dim path As String = String.Format("{0}s.{1}.n", subdirname, name)

    4.         If IO.File.Exists(path) Then

    5.             Return IO.File.ReadAllText(path)

    6.         Else

    7.             Return Nothing

    8.         End If

    9.     End Function

    10. End Class


  6. May 18th, 2013, 07:47 AM


    #6

    annaharris is offline


    Junior Member


    Re: implicit conversion from integer to string

    Which one is better and more preferred, implicit or explicit conversion.?


  7. May 18th, 2013, 09:10 AM


    #7

    Re: implicit conversion from integer to string

    Explicit conversions… that’s why the general recomendation is to set Option Explicit On by default.

    -tg


  8. May 18th, 2013, 09:46 AM


    #8

    Re: implicit conversion from integer to string

    Quote Originally Posted by techgnome
    View Post

    Explicit conversions… that’s why the general recomendation is to set Option Explicit On by default.

    -tg

    You mean Option Strict. Option Explicit has nothing to do with type conversions. Option Explicit determines whether explicit declaration of variables is required while Option Strict determines whether strict typing is enforced. Strict typing means no late binding and no implicit conversions.


  9. May 18th, 2013, 09:48 AM


    #9

    Re: implicit conversion from integer to string

    Quote Originally Posted by ident
    View Post

    ReadAllText returns a string value. Why are you casting this as an integer?

    Presumably because the file is a text file but it contains a setting value that represents a number. When you add an Integer to My.Settings it gets stored in the config file. The config file is XML, which is structured text. As such, the value has to be read as text and converted to an Integer at some point. This is no different.


  10. May 18th, 2013, 03:29 PM


    #10

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    The code I am using is from 2008 to 2009 so the code back then may of served its purpose. The code shown is part of the settings, the main app itself works fine and I have no issues with loading etc, I just got a warning on the code for implicit conversion from integer to string. Here is the settings functions, this is where I am getting the warning.

    Code:

    Imports System.IO
    
    ''' <summary>
    ''' Because My.Setting namespace loose it's data after renaming the assembly file, or moving it, i made this.
    ''' </summary>
    ''' <remarks></remarks>
    ''' 
    Public Module SettingsManager
    
        ' Dim subdirName As String = "opt"
        Dim subdirName As String = MYDIR & "opt"
    
        'Sub Check()
        '    If FileIO.FileSystem.DirectoryExists("opt") = False Then
        '        FileIO.FileSystem.CreateDirectory("opt")
        '    End If
        'End Sub
    
        Sub Check()
            If FileIO.FileSystem.DirectoryExists(subdirName) = False Then
                FileIO.FileSystem.CreateDirectory(subdirName)
            End If
        End Sub
    
        Function GetSettingInt(ByVal name As String) As Integer
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
                Return CInt(File.ReadAllText(subdirName & "s." & name & ".n"))
            Else
                Return Nothing
            End If
        End Function
    
        Function GetSettingStr(ByVal name As String) As String
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
                Return File.ReadAllText(subdirName & "s." & name & ".n")
            Else
                Return Nothing
            End If
        End Function
    
        ''' <summary>
        ''' Return an empty list if invalid name supplied.
        ''' </summary>
        ''' <param name="name"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Function GetSettingStrList(ByVal name As String) As List(Of String)
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
    
                Return File.ReadAllLines(subdirName & "s." & name & ".n").ToList()
    
            Else
                Return New List(Of String)(0)
            End If
        End Function
    
        Function GetSettingBool(ByVal name As String) As Boolean
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
    
                If File.ReadAllText(subdirName & "s." & name & ".n") = "True" Then
                    Return True
                Else
                    Return False
                End If
    
            Else
                Return Nothing
            End If
        End Function
    
        Sub SetSettingInt(ByVal name As String, ByVal data As Integer)
            Check()
            File.WriteAllText(subdirName & "s." & name & ".n", data)
        End Sub
    
        Sub SetSettingStr(ByVal name As String, ByVal str As String)
            Check()
            File.WriteAllText(subdirName & "s." & name & ".n", str)
        End Sub
    
        Sub SetSettingStrList(ByVal name As String, ByVal list As List(Of String))
            Check()
            File.WriteAllLines(subdirName & "s." & name & ".n", list.ToArray)
        End Sub
    
    
        Sub SetSettingBool(ByVal name As String, ByVal bool As Boolean)
            Check()
            File.WriteAllText(subdirName & "s." & name & ".n", bool.ToString)
        End Sub
    
    
        Sub SetSettingFont(ByVal name As String, ByVal font As Font)
            Check()
            'Dim d As New Font("font family", Size, FontStyle.Regular, GraphicsUnit.Pixel, font.GdiCharSet)
            Try
                Dim fontfamilyStr As String = font.FontFamily.Name
                Dim sizeStr As String = font.Size
                Dim styleStr As String = font.Style.ToString
                Dim gdiChatSet As String = CInt(font.GdiCharSet)
                Dim text As String = fontfamilyStr & "|" & sizeStr & "|" & styleStr & "|" & gdiChatSet
                File.WriteAllText(subdirName & "s." & name & ".n", text)
            Catch ex As Exception
            End Try
        End Sub
    
        Function getSettingFont(ByVal name As String) As Font
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
                Dim t As String() = File.ReadAllText(subdirName & "s." & name & ".n").Split(CChar("|"))
                Dim fontfamilyStr As String = t.ElementAt(0)
                Dim sizeStr As Single = CSng(t.ElementAt(1))
                Dim styleStr As FontStyle = getFontStyle(t.ElementAt(2))
                Dim gdiChatSet As Byte = CByte(t.ElementAt(3))
                Return New Font(fontfamilyStr, sizeStr, styleStr, GraphicsUnit.Point, gdiChatSet)
            Else
                Return Nothing
            End If
        End Function
    
        Private Function getFontStyle(ByVal s As String) As FontStyle
            Select Case s
                Case "Bold"
                    Return FontStyle.Bold
                Case "Italic"
                    Return FontStyle.Italic
                Case "Regular"
                    Return FontStyle.Regular
                Case "Strikeout"
                    Return FontStyle.Strikeout
                Case "Underline"
                    Return FontStyle.Underline
                Case Else
                    Return FontStyle.Regular
            End Select
        End Function
    
    End Module


  11. May 18th, 2013, 04:10 PM


    #11

    Re: implicit conversion from integer to string

    You’re getting the warning since GetSettingInt returns an integer and you’re assigning that to the Text property of a TextBox which is a String property. If you want to get rid of the warning use either of these two code lines:

    Code:

    TextBox14.Text = GetSettingInt("TMaxUPSpeed").ToString()
    'or
    TextBox14.Text = CStr(GetSettingInt("TMaxUPSpeed"))

    It’s always better to explicitly convert data types because you are in that case in control and the compiler doesn’t have to make assumptions of what you’re really trying to do. I would recommend to turn Option Strict on.

    Last edited by Joacim Andersson; May 18th, 2013 at 04:13 PM.


  12. May 18th, 2013, 06:53 PM


    #12

    Re: implicit conversion from integer to string

    File.ReadAllText() returns a string though, so I’m assuming that the text you want to read is supposed to be cast to an integer. I might suggest Integer.TryParse() in that case, and return either a null string, or string.Empty on false. (Check that accordingly, and do whatever you need to do based on the returned value.) Or make this function take on the paradigm of the TryParse() method using a ByRef param, and returning a boolean based on TryParse() success or failure…

    Since the value is being used for text though, why cast to an integer in the first place only to convert back to a string? Seems inefficient, and especially if you aren’t going to be using this Integer value for anything else. If you want validation Integer.TryParse() is the way to go…

    As mentioned above, unless you’ve changed your settings, Option Explicit is already on by default anyways, but Option Strict is the one that you want to have turned on. Implicit conversions are bad, and they also don’t teach you to recognize what types you are dealing with if you always rely in implicit conversions being done for you. I once read an article that had this as a defense somehow for why VB.net is better than C#… Not sure how that works, but that’s another story.

    Cheers

    Last edited by AceInfinity; May 18th, 2013 at 06:57 PM.

    <<<————


    .NET Programming (2012 — 2018)
    �Crestron — DMC-T Certified Programmer | Software Developer

    <<<————


  13. May 18th, 2013, 08:10 PM


    #13

    Re: implicit conversion from integer to string

    Quote Originally Posted by Joacim Andersson
    View Post

    You’re getting the warning since GetSettingInt returns an integer and you’re assigning that to the Text property of a TextBox which is a String property. If you want to get rid of the warning use either of these two code lines:

    Code:

    TextBox14.Text = GetSettingInt("TMaxUPSpeed").ToString()
    'or
    TextBox14.Text = CStr(GetSettingInt("TMaxUPSpeed"))

    It’s always better to explicitly convert data types because you are in that case in control and the compiler doesn’t have to make assumptions of what you’re really trying to do. I would recommend to turn Option Strict on.

    Which is exactly what I said in post #3, so one wonders why the OP is still asking the same question and hasn’t acted on the advice provided there.


  14. May 18th, 2013, 08:16 PM


    #14

    Re: implicit conversion from integer to string

    Quote Originally Posted by AceInfinity
    View Post

    Since the value is being used for text though, why cast to an integer in the first place only to convert back to a string? Seems inefficient, and especially if you aren’t going to be using this Integer value for anything else.

    You seem to be missing the point that I made in post #9. It’s clear from the method name that this data represents part of the application’s preferences/options/settings. The data obviously represents a number so it is completely appropriate that it be returned as a number. When the data gets used it will be used as a number. This is presumably not the only place that this setting value will be used. This particular instance is for display purposes so, as with all data, it must be in String form for that purpose. Elsewhere though, it is likely that the data will be used in a comparison with another number, so it is essential that it be a number. Would you say that My.Settings should return everything as Strings? If not then why should these home-grown settings be returned as Strings?

    The possibility that the file doesn’t contain a valid number has to be taken into account somewhere. If your suggestion to use TryParse is not taken up then any code that calls this method really should have it within an exception handler.


  15. May 18th, 2013, 08:38 PM


    #15

    Re: implicit conversion from integer to string

    Quote Originally Posted by jmcilhinney
    View Post

    You seem to be missing the point that I made in post #9. It’s clear from the method name that this data represents part of the application’s preferences/options/settings. The data obviously represents a number so it is completely appropriate that it be returned as a number. When the data gets used it will be used as a number. This is presumably not the only place that this setting value will be used. This particular instance is for display purposes so, as with all data, it must be in String form for that purpose. Elsewhere though, it is likely that the data will be used in a comparison with another number, so it is essential that it be a number. Would you say that My.Settings should return everything as Strings? If not then why should these home-grown settings be returned as Strings?

    The possibility that the file doesn’t contain a valid number has to be taken into account somewhere. If your suggestion to use TryParse is not taken up then any code that calls this method really should have it within an exception handler.

    Quote Originally Posted by jmcilhinney
    View Post

    Presumably because the file is a text file but it contains a setting value that represents a number. When you add an Integer to My.Settings it gets stored in the config file. The config file is XML, which is structured text. As such, the value has to be read as text and converted to an Integer at some point. This is no different.

    You are probably right. And if he uses this value lots of times as an Integer, I suppose a simple redundant cast back to a string wouldn’t matter too much. He wouldn’t have to cast the value to an Integer a whole bunch of times though when he wants to use it if the return value stays as is. I didn’t consider the bigger picture and was only looking at the smaller inefficiency here, because I have a habit of only reading the thread and judging based on the given information.

    Regards,
    Ace

    Last edited by AceInfinity; May 18th, 2013 at 09:03 PM.

    <<<————


    .NET Programming (2012 — 2018)
    �Crestron — DMC-T Certified Programmer | Software Developer

    <<<————


  16. May 18th, 2013, 10:38 PM


    #16

    Re: implicit conversion from integer to string

    why is everyone talking about conversions, the question was what does the line of code do

    TextBox14.Text = GetSettingInt(«TMaxUPSpeed»)

    and

    Function GetSettingInt(ByVal name As String) As Integer
    Check()
    If FileIO.FileSystem.FileExists(subdirName & «s.» & name & «.n») = True Then
    Return CInt(File.ReadAllText(subdirName & «s.» & name & «.n»))
    Else
    Return Nothing
    End If
    End Function

    simply checks if a file named «TMaxUpSpeed» exists
    if it does it puts the contents of the file ( an intergeter probably) in a textbox, its wrongly coded and conversions dont need to be applied
    if it does not then the textbox is left empty

    it seems a little pointless(with the way its done) but thats what its doing

    its that simple.

    why are all u guys confusing jokerfool by following up with the conversions stuff?

    Last edited by GBeats; May 18th, 2013 at 10:42 PM.

    Yes!!!
    Working from home is so much better than working in an office…
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR’s power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O’clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  17. May 18th, 2013, 10:45 PM


    #17

    Re: implicit conversion from integer to string

    Function GetSettingInt(ByVal name As String) As Integer
    Check()
    If FileIO.FileSystem.FileExists(subdirName & «s.» & name & «.n») = True Then
    Return CInt(File.ReadAllText(subdirName & «s.» & name & «.n»))
    Else
    Return Nothing
    End If
    End Function

    should be

    Function GetSettingInt(ByVal name As String)

    As string
    Check()
    If FileIO.FileSystem.FileExists(subdirName & «s.» & name & «.n») = True Then
    Return File.ReadAllText(subdirName & «s.» & name & «.n»)
    Else
    Return Nothing
    End If
    End Function

    Yes!!!
    Working from home is so much better than working in an office…
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR’s power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O’clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  18. May 18th, 2013, 11:30 PM


    #18

    Re: implicit conversion from integer to string

    Why? If the text in the file is an integer why shouldn’t the function return an integer? It would be safer to use Integer.TryParse than CInt but the function is still returning an integer, and (unless the function causes an exception) the textbox will never be empty since the function is always returning an integer. Nothing for an integer is equal to 0.

    The warning is because the integer that is returned is added to a textbox and should first be converted as posted earlier.


  19. May 19th, 2013, 12:21 AM


    #19

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    So I just want to clarify that the code I am using is from 2008, please understand this, I didn’t write the code, I am just asking for assistance. So thank you to the posts, I will take everything on board and make the changes. Thank you.


  20. May 19th, 2013, 12:31 AM


    #20

    Re: implicit conversion from integer to string

    Quote Originally Posted by GBeats
    View Post

    should be

    Function GetSettingInt(ByVal name As String)

    As string
    Check()
    If FileIO.FileSystem.FileExists(subdirName & «s.» & name & «.n») = True Then
    Return File.ReadAllText(subdirName & «s.» & name & «.n»)
    Else
    Return Nothing
    End If
    End Function

    If the return value was a string, then GetSettingInt wouldn’t make sense would it? And this was part of the discussion if you look through the thread.

    The setting is intended to be an Integer from the very beginning, so why should it be a string? You’re going to be using it perhaps more as an Integer than a String, so for this one place where you would use it as a string, why would you make the function fit this type? Then all the other places where you use it as an Integer, you have to manually cast it each time, instead of returning that value directly from the function.

    And no… He was asking what the implicit conversion bit meant on that line, not what the code itself does.

    Being new to programming, can someone explain to me in the most basic format what exactly this means, what does implicit conversion mean and implicit conversion from integer to string mean, what is it trying to tell me here?

    When he said «can someone explain to me in the most basic format what exactly this means,» he was referencing the implicit conversion notice.

    My suggestion was Integer.TryParse(), so if you didn’t have the return value as an Integer, then imagine implementing TryParse() everywhere you use this string, just to have a usable integer representation of the text in the file? Rethinking this over, it makes much more sense to stay an Integer.

    ~Ace

    Last edited by AceInfinity; May 19th, 2013 at 12:36 AM.

    <<<————


    .NET Programming (2012 — 2018)
    �Crestron — DMC-T Certified Programmer | Software Developer

    <<<————


  21. May 19th, 2013, 12:36 AM


    #21

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    OMG Integer or String, its all too much for me now, im so confused and it doesnt matter who explains it except for post #2, I think I understand.

    This post was never intended to be a debate, I had the warning when I go to build, it didnt stop the function of the app, I just wanted to know how to remove the warning, it seems I will have to edit the code in the settings file as explained above and in doing so it has removed the error from certain lines and now refers to other lines in the settings file e.g. SetSettingInt, but there are hundreds of lines related to that error, would this mean going in and changing all those lines from int to str? I am sorry if I am not the expert here I am only the beginner and trying to learn as much as I can before the end of the line arrives for me, but thank you too all.


  22. May 19th, 2013, 12:41 AM


    #22

    Re: implicit conversion from integer to string

    Why is it too much? What are you confused about? Let us know and we can help.

    Post #3, is where the implicit conversion phenomena is best explained in my opinion: http://www.vbforums.com/showthread.p…=1#post4417245

    The return value from the function is an Integer, the Text property when set, expects a type of string, so when you assign that Integer to the placeholder of the Text property, a magical conversion is done for you (an implicit conversion from the original Integer, to the String value). To avoid the «magician» doing this magic for you so to speak, you need to cast that Integer value to a string first before you assign it to the Text property. That’s how you would fix it.

    So as mentioned above, either CStr(), or the ToString() extension method.

    it seems I will have to edit the code in the settings file as explained above

    No, that function is fine… The only modification you might consider making to it, is adding Integer.TryParse() in there instead of CInt(). Everything else is fine, you shouldn’t need to do anything with the function…

    <<<————


    .NET Programming (2012 — 2018)
    �Crestron — DMC-T Certified Programmer | Software Developer

    <<<————


  23. May 19th, 2013, 12:44 AM


    #23

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    Ahhhh lightbulb to head

    The textbox with the error is a text box that requires the user to enter a number

    Which I believe is the Integer.

    What is the meaning of implicit conversion, I dont get.

    So it wants to change from a number to a letter is that what this error is referring too?


  24. May 19th, 2013, 12:45 AM


    #24

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    AceInfinity I was referring too

    String «The Quick Brown Fox…»
    Integer 8 etc..


  25. May 19th, 2013, 12:48 AM


    #25

    Re: implicit conversion from integer to string

    So it wants to change from a number to a letter is that what this error is referring too?

    By «letter», the proper term is String, but yes.

    The Text property is a type of String. Thus it doesn’t accept an Integer. Some kind of conversion needs to happen to get the value to a type of String, before the Text property can hold that value. So if you don’t have Option Strict On, and you don’t do this conversion yourself (explicitly), an implicit conversion happens and this conversion is dealt with for you automatically (when a conversion can be made). This is bad practice though and should be avoided, so that’s why you are getting the notification about it.

    <<<————


    .NET Programming (2012 — 2018)
    �Crestron — DMC-T Certified Programmer | Software Developer

    <<<————


  26. May 19th, 2013, 12:48 AM


    #26

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    When I change to .ToString() it says:

    Expression does not produce a value

    Hence why I didnt change anything further

    Should I turn on Option Strict On and if so how?


  27. May 19th, 2013, 12:51 AM


    #27

    Re: implicit conversion from integer to string

    Quote Originally Posted by jokerfool
    View Post

    When I change to .ToString() it says:

    Expression does not produce a value

    Hence why I didnt change anything further

    Did you do:

    Code:

    TextBox14.Text = GetSettingInt("TMaxUPSpeed").ToString()

    ???

    And to imagine this implicit conversion stuff. Lets say that the GetSettingInt() function returns a value of 9 in this case.

    If you write this in your code:

    You will get the same warning. But the implicit conversion takes that 9 and makes it «9» (a string). This would fix that warning:

    Code:

    TextBox14.Text = "9"

    Or in this case 9 is a placeholder for our function (we can’t just put quotes around the function, otherwise it makes the function name our string, and not its return value), so the ToString() function is used:

    Code:

    TextBox14.Text = (9).ToString()

    <<<————


    .NET Programming (2012 — 2018)
    �Crestron — DMC-T Certified Programmer | Software Developer

    <<<————


  28. May 19th, 2013, 01:12 AM


    #28

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    I did add the .tostring but I got that error above. Instead I added this code as mentioned and the error went away

    Code:

    Function GetSettingInt(ByVal name As String) As String
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
                Return File.ReadAllText(subdirName & "s." & name & ".n")
            Else
                Return Nothing
            End If
        End Function


  29. May 19th, 2013, 01:27 AM


    #29

    Re: implicit conversion from integer to string

    Hi,

    ok yes i read it again, i missed your post.

    and since it looks like its getting some sort of setting that’s numerical then it makes sense to have the function like that.
    i wasnt thinking but practically its a good way to get «0» in the string if there is nothing there, since naturally integers start of as 0.

    point taken sry
    the function still is has potential problems with the way it is, and is relying of outside information being correct to prevent a crash.

    Yes!!!
    Working from home is so much better than working in an office…
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR’s power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O’clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  30. May 19th, 2013, 01:31 AM


    #30

    Re: implicit conversion from integer to string

    jokerfool please NOTE

    if the function is used somewhere else while code like my suggestion, you will need to do more conversions, but if its not then you will be fine.

    the error you have might also be caused by the file itself, you should check the data inside the file.

    obviously you cant use Cint(«with this») because there are no numbers there, i dont know what it would return but it wouldnt be what you wanted that is sure.

    Yes!!!
    Working from home is so much better than working in an office…
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR’s power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O’clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  31. May 19th, 2013, 01:32 AM


    #31

    Re: implicit conversion from integer to string

    Quote Originally Posted by jokerfool
    View Post

    I did add the .tostring but I got that error above. Instead I added this code as mentioned and the error went away

    Code:

    Function GetSettingInt(ByVal name As String) As String
            Check()
            If FileIO.FileSystem.FileExists(subdirName & "s." & name & ".n") = True Then
                Return File.ReadAllText(subdirName & "s." & name & ".n")
            Else
                Return Nothing
            End If
        End Function

    No… Please read through the posts again, it was suggested not to do this as a final consensus.

    Does this make sense?

    1. GetSettingInt
    2. Return value: String

    What was the error you were getting with ToString()?

    <<<————


    .NET Programming (2012 — 2018)
    �Crestron — DMC-T Certified Programmer | Software Developer

    <<<————


  32. May 19th, 2013, 01:42 AM


    #32

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    When I change to .ToString() it says:

    Expression does not produce a value


  33. May 19th, 2013, 01:43 AM


    #33

    Re: implicit conversion from integer to string

    I have a hard time believing that you’re using the function correctly.. Can you show us your exact code when it gives you that error and are you sure it is with that line?

    <<<————


    .NET Programming (2012 — 2018)
    �Crestron — DMC-T Certified Programmer | Software Developer

    <<<————


  34. May 19th, 2013, 01:45 AM


    #34

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    Already did that, its posted above.


  35. May 19th, 2013, 01:46 AM


    #35

    Re: implicit conversion from integer to string

    Quote Originally Posted by jokerfool
    View Post

    When I change to .ToString() it says:

    Expression does not produce a value

    Then you did it wrong. How about you show us what you did and then we can tell you what’s wrong with it?


  36. May 19th, 2013, 01:59 AM


    #36

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    Okay I guess I must of made a mistake somewhere, so is this correct? Cos the line is no longer highlighted saying that message, but will adding that .ToString() to the end of the line chance the functionality of the application?

    TextBox14.Text = GetSettingInt(«TMaxUPSpeed»).ToString()


  37. May 19th, 2013, 02:00 AM


    #37

    Re: implicit conversion from integer to string

    you should double check the file that you getting the info for, your applying a text extraction, maybe the file contains an object, or nothing at all.

    you said you already changed the function to return string, what did the textbox show when you did that?

    Yes!!!
    Working from home is so much better than working in an office…
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR’s power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O’clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  38. May 19th, 2013, 02:08 AM


    #38

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string

    When I made that change you mentioned the error for that section disappeared, the error moved onto another section within the settings that I mentioned above


  39. May 19th, 2013, 02:15 AM


    #39

    Re: implicit conversion from integer to string

    Quote Originally Posted by jokerfool
    View Post

    Okay I guess I must of made a mistake somewhere, so is this correct? Cos the line is no longer highlighted saying that message, but will adding that .ToString() to the end of the line chance the functionality of the application?

    TextBox14.Text = GetSettingInt(«TMaxUPSpeed»).ToString()

    No it won’t. Either way, the number is being retrieved from the file and displayed in the TextBox. The difference is that the ToString means that the Integer is converted to a String explicitly while previously it was being converted implicitly. It’s being converted either way though. Do you actually know what implicit and explicit mean? That would probably be a good place to start.


  40. May 19th, 2013, 02:24 AM


    #40

    jokerfool is offline

    Thread Starter


    Hyperactive Member

    jokerfool's Avatar


    Re: implicit conversion from integer to string


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • VS 2012 [RESOLVED]implicit conversion from integer to string


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

100

File reading error

101

Error of opening an *. EX4 for writing

103

Not enough free memory to complete compilation

104

Empty syntactic unit unrecognized by compiler

105

Incorrect file name in #include

106

Error accessing a file in #include (probably the file does not exist)

108

Inappropriate name for #define

109

Unknown command of preprocessor (valid #include, #define, #property, #import)

110

Symbol unknown to compiler

111

Function not implemented (description is present, but no body)

112

Double quote («) omitted

113

Opening angle bracket (<) or double quote («) omitted

114

Single quote (‘) omitted

115

Closing angle bracket «>» omitted

116

Type not specified in declaration

117

No return operator or return is found not in all branches of the implementation

118

Opening bracket of call parameters was expected

119

Error writing EX4

120

Invalid access to an array

121

The function is not of void type and the return operator must return a value

122

Incorrect declaration of the destructor

123

Colon «:» is missing

124

Variable is already declared

125

Variable with such identifier already declared

126

Variable name is too long (> 250 characters)

127

Structure with such identifier already defined

128

Structure is not defined

129

Structure member with the same name already defined

130

No such structure member

131

Breached pairing of brackets

132

Opening parenthesis «(» expected

133

Unbalanced braces (no «}»)

134

Difficult to compile (too much branching, internal stack levels are overfilled)

135

Error of file opening for reading

136

Not enough memory to download the source file into memory

137

Variable is expected

138

Reference cannot be initialized

140

Assignment expected (appears at declaration)

141

Opening brace «{» expected

142

Parameter can be a dynamic array only

143

Use of «void» type is unacceptable

144

No pair for «)» or «]», i.e. «(or» [ » is absent

145

No pair for «(or» [ «, i.e. «) «or»] » is absent

146

Incorrect array size

147

Too many parameters (> 64)

149

This token is not expected here

150

Invalid use of operation (invalid operands)

151

Expression of void type not allowed

152

Operator is expected

153

Misuse of break

154

Semicolon «;» expected

155

Comma «,» expected

156

Must be a class type, not struct

157

Expression is expected

158

«non HEX character» found in HEX or too long number (number of digits> 511)

159

String-constant has more than 65534 characters

160

Function definition is unacceptable here

161

Unexpected end of program

162

Forward declaration is prohibited for structures

163

Function with this name is already defined and has another return type

164

Function with this name is already defined and has a different set of parameters

165

Function with this name is already defined and implemented

166

Function overload for this call was not found

167

Function with a return value of void type cannot return a value

168

Function is not defined

170

Value is expected

171

In case expression only integer constants are valid

172

The value of case in this switch is already used

173

Integer is expected

174

In #import expression file name is expected

175

Expressions are not allowed on global level

176

Omitted parenthesis «)» before «;»

177

To the left of equality sign a variable is expected

178

The result of expression is not used

179

Declaring of variables is not allowed in case

180

Implicit conversion from a string to a number

181

Implicit conversion of a number to a string

182

Ambiguous call of an overloaded function (several overloads fit)

183

Illegal else without proper if

184

Invalid case or default without a switch

185

Inappropriate use of ellipsis

186

The initializing sequence has more elements than the initialized variable

187

A constant for case expected

188

A constant expression required

189

A constant variable cannot be changed

190

Closing bracket or a comma is expected (declaring array member)

191

Enumerator identifier already defined

192

Enumeration cannot have access modifiers (const, extern, static)

193

Enumeration member already declared with a different value

194

There is a variable defined with the same name

195

There is a structure defined with the same name

196

Name of enumeration member expected

197

Integer expression expected

198

Division by zero in constant expression

199

Wrong number of parameters in the function

200

Parameter by reference must be a variable

201

Variable of the same type to pass by reference expected

202

A constant variable cannot be passed by a non-constant reference

203

Requires a positive integer constant

204

Failed to access protected class member

205

Import already defined in another way

208

Executable file not created

209

‘OnCalculate’ entry point not found for the indicator

210

The continue operation can be used only inside a loop

211

Error accessing private (closed) class member

213

Method of structure or class is not declared

214

Error accessing private (closed) class method

216

Copying of structures with objects is not allowed

218

Index out of array range

219

Array initialization in structure or class declaration not allowed

220

Class constructor cannot have parameters

221

Class destructor can not have parameters

222

Class method or structure with the same name and parameters have already been declared

223

Operand expected

224

Class method or structure with the same name exists, but with different parameters (declaration!=implementation)

225

Imported function is not described

226

ZeroMemory() is not allowed for objects with protected members or inheritance

227

Ambiguous call of the overloaded function (exact match of parameters for several overloads)

228

Variable name expected

229

A reference cannot be declared in this place

230

Already used as the enumeration name

232

Class or structure expected

235

Cannot call ‘delete’ operator to delete the array

236

Operator ‘ while’ expected

237

Operator ‘delete’ must have a pointer

238

There is ‘default’ for this ‘switch’ already

239

Syntax error

240

Escape-sequence can occur only in strings (starts with »)

241

Array required — square bracket ‘[‘ does not apply to an array, or non arrays are passed as array parameters

242

Can not be initialized through the initialization sequence

243

Import is not defined

244

Optimizer error on the syntactic tree

245

Declared too many structures (try to simplify the program)

246

Conversion of the parameter is not allowed

247

Incorrect use of the ‘delete’ operator

248

It’s not allowed to declare a pointer to a reference

249

It’s not allowed to declare a reference to a reference

250

It’s not allowed to declare a pointer to a pointer

251

Structure declaration in the list of parameter is not allowed

252

Invalid operation of typecasting

253

A pointer can be declared only for a class or structure

256

Undeclared identifier

257

Executable code optimizer error

258

Executable code generation error

260

Invalid expression for the ‘switch’ operator

261

Pool of string constants overfilled, simplify program

262

Cannot convert to enumeration

263

Do not use ‘virtual’ for data (members of a class or structure)

264

Cannot call protected method of class

265

Overridden virtual functions return a different type

266

Class cannot be inherited from a structure

267

Structure cannot be inherited from a class

268

Constructor cannot be virtual (virtual specifier is not allowed)

269

Method of structure cannot be virtual

270

Function must have a body

271

Overloading of system functions (terminal functions) is prohibited

272

Const specifier is invalid for functions that are not members of a class or structure

274

Not allowed to change class members in constant method

276

Inappropriate initialization sequence

277

Missed default value for the parameter (specific declaration of default parameters)

278

Overriding the default parameter (different values in declaration and implementation)

279

Not allowed to call non-constant method for a constant object

280

An object is necessary for accessing members (a dot for a non class/structure is set)

281

The name of an already declared structure cannot be used in declaration

284

Unauthorized conversion (at closed inheritance)

285

Structures and arrays cannot be used as input variables

286

Const specifier is not valid for constructor/destructor

287

Incorrect string expression for a datetime

288

Unknown property (#property)

289

Incorrect value of a property

290

Invalid index for a property in #property

291

Call parameter omitted — <func (x,)>

293

Object must be passed by reference

294

Array must be passed by reference

295

Function was declared as exportable

296

Function was not declared as exportable

297

It is prohibited to export imported function

298

Imported function cannot have this parameter (prohibited to pass a pointer, class or structure containing a dynamic array, pointer, class, etc.)

299

Must be a class

300

#import was not closed

302

Type mismatch

303

Extern variable is already initialized

304

No exported function or entry point found

305

Explicit constructor call is not allowed

306

Method was declared as constant

307

Method was not declared as constant

308

Incorrect size of the resource file

309

Incorrect resource name

310

Resource file opening error

311

Resource file reading error

312

Unknown resource type

313

Incorrect path to the resource file

314

The specified resource name is already used

315

Argument expected for the function-like macro

316

Unexpected symbol in macro definition

317

Error in formal parameters of the macro

318

Invalid number of parameters for a macro

319

Too many parameters for a macro

320

Too complex, simplify the macro

321

Parameter for EnumToString() can be only an enumeration

322

The resource name is too long

323

Unsupported image format (only BMP with 24 or 32 bit color depth is supported)

324

An array cannot be declared in operator

325

The function can be declared only in the global scope

326

The declaration is not allowed for the current scope

327

Initialization of static variables with the values of local variables is not allowed

328

Illegal declaration of an array of objects that do not have a default constructor

329

Initialization list allowed only for constructors

330

No function definition after initialization list

331

Initialization list is empty

332

Array initialization in a constructor is not allowed

333

Initializing members of a parent class in the initialization list is not allowed

334

Expression of the integer type expected

335

Memory required for the array exceeds the maximum value

336

Memory required for the structure exceeds the maximum value

337

Memory required for the variables declared on the global level exceeds the maximum value

338

Memory required for local variables exceeds the maximum value

339

Constructor not defined

340

Invalid name of the icon file

341

Could not open the icon file at the specified path

342

The icon file is incorrect and is not of the ICO format

343

Reinitialization of a member in a class/structure constructor using the initialization list

344

Initialization of static members in the constructor initialization list is not allowed

345

Initialization of a non-static member of a class/structure on a global level is not allowed

346

The name of the class/structure method matches the name of an earlier declared member

347

The name of the class/structure member matches the name of an earlier declared method

348

Virtual function cannot be declared as static

349

The const modifier is not allowed for static functions

350

Constructor or destructor cannot be static

351

Non-static member/method of a class or a structure cannot be accessed from a static function

352

An overload operation (+,-,[],++,— etc.) is expected after the operator keyword

353

Not all operations can be overloaded in MQL4

354

Definition does not match declaration

355

An invalid number of parameters is specified for the operator

356

Event handling function not found

357

Method cannot be exported

358

A pointer to the constant object cannot be normalized by a non-constant object

359

Class templates are not supported yet

360

Function template overload is not supported yet

361

Function template cannot be applied

362

Ambiguous parameter in function template (several parameter types can be applied)

363

Unable to determine the parameter type, by which the function template argument should be normalized

364

Incorrect number of parameters in the function template

365

Function template cannot be virtual

366

Function templates cannot be exported

367

Function templates cannot be imported

368

Structures containing the objects are not allowed

369

String arrays and structures containing the objects are not allowed

370

A static class/structure member must be explicitly initialized

371

Compiler limitation: the string cannot contain more than 65 535 characters

372

Inconsistent #ifdef/#endif

373

Object of class cannot be returned, copy constructor not found

374

Non-static members and methods cannot be used

375

OnTesterInit() impossible to use without OnTesterDeinit()

376

Redefinition of formal parameter ‘%s’

377

Macro __FUNCSIG__ and __FUNCTION__ cannot appear outside of a function body

378

Invalid returned type. For example, this error will be produced for functions imported from DLL that return structure or pointer.

379

Template usage error

380

Not used

381

Illegal syntax when declaring pure virtual function, only «=NULL» or «=0» are allowed

382

Only virtual functions can be declared with the pure-specifier («=NULL» or «=0»)

383

Abstract class cannot be instantiated

384

A pointer to a user-defined type should be applied as a target type for dynamic casting using the dynamic_cast operator

385

«Pointer to function» type is expected

386

Pointers to methods are not supported

387

Error — cannot define the type of a pointer to function

388

Type cast is not available due to private inheritance

389

A variable with const modifier should be initialized during declaration

Понравилась статья? Поделить с друзьями:
  • Imped error перевод
  • Imp 00017 following statement failed with oracle error 1917
  • Imp 00003 oracle error 942 encountered
  • Immobilizer transponder error
  • Ilink64 error fatal out of memory