Error cs0019 operator cannot be applied to operands of type string and string

Compiler Error Message: CS0019: Operator '||' cannot be applied to operands of type 'string' and 'string'

RRS feed

  • Remove From My Forums
  • Question

  • Compiler Error Message: CS0019: Operator ‘||’ cannot be applied to operands of type ‘string’ and ‘string’

    Source Error:

    Line 80:     {
    Line 81:
    Line 82: if ((TextBoxVoornaam.Text = "") || (TextBoxFamilienaam.Text = ""))
    Line 83: {
    Line 84: LabelError.Text = "U dient alle velden in te vullen";

    Source File: c:Documents and SettingsEigenaarBureaublad!!GIP!!WebsiteDefault.aspx.cs    Line: 82

Answers

  •  proggie wrote:
    Compiler Error Message: CS0019: Operator ‘||’ cannot be applied to operands of type ‘string’ and ‘string’

    Source Error:

    Line 80:     {
    Line 81:
    Line 82: if ((TextBoxVoornaam.Text = "") || (TextBoxFamilienaam.Text = ""))
    Line 83: {
    Line 84: LabelError.Text = "U dient alle velden in te vullen";

    Source File: c:Documents and SettingsEigenaarBureaublad!!GIP!!WebsiteDefault.aspx.cs    Line: 82

    The operator || as well as | cannot be applied to string objects. It is a comparison operator for boolean types.

    You can use this operator in expressions like this:

    if ( string1 != string.Empty || string2 != string.Empty)

    {

    }

    Your problem is that instead of boolean == you are using assignment operator =.

    Change it into:

    if ((TextBoxVoornaam.Text == «») || (TextBoxFamilienaam.Text == «»))


All replies

  •  proggie wrote:
    Compiler Error Message: CS0019: Operator ‘||’ cannot be applied to operands of type ‘string’ and ‘string’

    Source Error:

    Line 80:     {
    Line 81:
    Line 82: if ((TextBoxVoornaam.Text = "") || (TextBoxFamilienaam.Text = ""))
    Line 83: {
    Line 84: LabelError.Text = "U dient alle velden in te vullen";

    Source File: c:Documents and SettingsEigenaarBureaublad!!GIP!!WebsiteDefault.aspx.cs    Line: 82

    The operator || as well as | cannot be applied to string objects. It is a comparison operator for boolean types.

    You can use this operator in expressions like this:

    if ( string1 != string.Empty || string2 != string.Empty)

    {

    }

    Your problem is that instead of boolean == you are using assignment operator =.

    Change it into:

    if ((TextBoxVoornaam.Text == «») || (TextBoxFamilienaam.Text == «»))


  •  AlexBB wrote:

     proggie wrote:
    Compiler Error Message: CS0019: Operator ‘||’ cannot be applied to operands of type ‘string’ and ‘string’

    Source Error:

    Line 80:     {
    Line 81:
    Line 82: if ((TextBoxVoornaam.Text = "") || (TextBoxFamilienaam.Text = ""))
    Line 83: {
    Line 84: LabelError.Text = "U dient alle velden in te vullen";

    Source File: c:Documents and SettingsEigenaarBureaublad!!GIP!!WebsiteDefault.aspx.cs    Line: 82

    The operator || as well as | cannot be applied to string objects. It is a comparison operator for boolean types.

    You can use this operator in expressions like this:

    if ( string1 != string.Empty || string2 != string.Empty)

    {

    }

    Your problem is that instead of boolean == you are using assignment operator =.

    Change it into:

    if ((TextBoxVoornaam.Text == «») || (TextBoxFamilienaam.Text == «»))

    Done.

    UnDone.


  • To continue from Alex’s post and add an improvement in the condition checks. This is how your code should look like:

    Code Snippet

    if ((TextBoxVoornaam.Text.Length == 0) || (TextBoxFamilienaam.Text.Length == 0))

    {

       LabelError.Text = «U dient alle velden in te vullen»;

    }

  •  Rudedog2 wrote:

    Please mark this answer as correct.

    Thanks, Rudedog, it was not quite rude of youSmile

    My problem is that I am not in competition for a job, or MVP title, or anything of this nature. I am not in a career track. Aquiring stars actually makes me rather antsy, they have an opposite effect. I want clarity and knowledge for my own sake and with growing «stardom» I feel that I still know very little as compared to many other people and feel less comfortable posting. It is a nonlinear rewared system.

    I would appreciate if you actually delete that post.

    Thanks.


  •  boban.s wrote:

    To continue from Alex’s post and add an improvement in the condition checks. This is how your code should look like:

    Code Snippet

    if ((TextBoxVoornaam.Text.Length == 0) || (TextBoxFamilienaam.Text.Length == 0))

    {

       LabelError.Text = «U dient alle velden in te vullen»;

    }


    Hi Bob, I think there might be a little problem in here. I mean in general so to speak. Let’s assume that he gets his string from an rtf file and it has two characrers in front: tn or whatever and nothing more.

    There is a chance that the length of this string will be 2 and the string still be «empty» string.Empty == true; because they are WhiteSpace characters.

    Look:


    string str = string.Empty;

    str += ‘n’;

    str += ‘t’;

    Console.WriteLine ( str.Length.ToString ( ) + » « + string.Compare ( str, string.Empty ).ToString ( ) );

    Console.WriteLine ( str.Length.ToString ( ) + » « + str.CompareTo ( string.Empty ).ToString ( ) )

    The result was

    2 1

    2 1

    Obviously 1 means they are equal.

    I don’t know what he actuall want, though with this statement.


  •  AlexBB wrote:

     Rudedog2 wrote:

    Please mark this answer as correct.

    Thanks, Rudedog, it was not quite rude of you

    My problem is that I am not in competition for a job, or MVP title, or anything of this nature. I am not in a career track. Aquiring stars actually makes me rather antsy, they have an opposite effect. I want clarity and knowledge for my own sake and with growing «stardom» I feel that I still know very little as compared to many other people and feel less comfortable posting. It is a nonlinear rewared system.

    I would appreciate if you actually delete that post.

    Thanks.

    Not in any sort of competition either.  Just helping folks find answers, and like you learning stuff along the way.


  •  Rudedog2 wrote:

     AlexBB wrote:

     Rudedog2 wrote:

    Please mark this answer as correct.


    Not in any sort of competition either.  Just helping folks find answers, and like you learning stuff along the way.

    Thanks you and I appreciate your comment. It makes me feel I am not alone.


  • Compiler Error Message: CS0019: Operator ‘||’ cannot be applied to operands of type ‘string’ and ‘string’

    Source Error:

    Line 80:     {
    Line 81:
    Line 82: if ((TextBoxVoornaam.Text = "") || (TextBoxFamilienaam.Text = ""))
    Line 83: {
    Line 84: LabelError.Text = "U dient alle velden in te vullen";

    Source File: c:Documents and SettingsEigenaarBureaublad!!GIP!!WebsiteDefault.aspx.cs    Line: 82

    In all reality you probably want to use the string.IsNullorEmpty(myString) function in this case but the below should work if you’re trying to compare the 2 strings.

    if ((TextBoxVoornaam.Text.ToString().Equals("")) || (TextBoxFamilienaam.Text.ToString().Equals("")))

    • Proposed as answer by

      Monday, December 7, 2009 3:59 PM

  • This thread has pretty much run out of life.  Check out the dates.


    Mark the best replies as answers. «Fooling computers since 1971.»

  • if (answer.Text == option1.Text || answer.Text == option2.Text || answer.Text == option3.Text || answer.Text == option4.Text)

    this is how we should do or else u will get an error u mentioned above


I want to my code to cater for Small letter and Capital letter string values. when I use || operator in Visual studio 2022 I get this error «CS0019: Operator ‘||’ cannot be applied to operands of type ‘string’ and ‘string'» but when I change to «or» it works on visual studio 2022 but when I compile the code outside of visual studio I get the same error «CS0019: Operator ‘||’ cannot be applied to operands of type ‘string’ and ‘string'». Is there another way can user or operator that will make on any environment. C# console application

see code below:

switch (value) { case "A" or "a": cardValue = 11; break; case "J" or "j": cardValue = 11; break; case "Q" or "q": cardValue = 12; break; case "K" or "k": cardValue = 13; break; }

I tried using

case "A" or "a": cardValue = 11; break;

and
case "A" || "a": cardValue = 11; break;

asked Jan 19 at 21:17

Siphamandla Dimba's user avatar

1

Use it like this: add each option as below example A and a are added.

switch(value)
{
    case a:
    case A:
    ...do something....
    break;
}

answered Jan 19 at 21:31

MDC's user avatar

0

0 / 0 / 0

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

Сообщений: 14

1

12.04.2019, 16:28. Показов 7121. Ответов 12


Помогите решить проблему, не могу понять что я не правильно сделал в коде

Миниатюры

CS0019 Оператор "&&" невозможно применить к операнду типа "string" и "string"
 

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



0



1123 / 794 / 219

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

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

12.04.2019, 16:35

2

Цитата
Сообщение от FuKs1k
Посмотреть сообщение

что я не правильно сделал

вставили код картинкой

Цитата
Сообщение от FuKs1k
Посмотреть сообщение

Помогите решить проблему

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



0



0 / 0 / 0

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

Сообщений: 14

12.04.2019, 16:39

 [ТС]

3

Покажите пожалуйста куда это нужно прописывать и как именно



0



1123 / 794 / 219

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

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

12.04.2019, 16:42

4

Цитата
Сообщение от FuKs1k
Посмотреть сообщение

Покажите пожалуйста куда это нужно прописывать и как именно

то есть я должен с картинки ручками переписать ваш код и исправить? и это вместо двух кликов «копировать-вставить»?



0



0 / 0 / 0

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

Сообщений: 14

12.04.2019, 16:45

 [ТС]

5

Прикрепил проект, посмотрите пожалуйста



0



КОП

12.04.2019, 16:46

Не по теме:

я не знаю как донести мысль, я сдаюсь



0



FuKs1k

0 / 0 / 0

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

Сообщений: 14

12.04.2019, 16:50

 [ТС]

7

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 private string number;
        public string Number
        {
            set
            {
                if (("value < 100000000000") && ("value >= 70000000000") && ("value / 10000000000 == 7"))
                {
                    number = value;
                }
 
                else
                {
                    throw new ArgumentException("Телефон должен быть введен корректно(начинаться с 7 и иметь длинну 11 цифр");
                }
 
            }
 
            get
            {
                return number;
            }

Добавлено через 2 минуты
Куда мне int.parse() прописать?
Либо как сделать номер числом?



0



Kazbek17

1346 / 835 / 419

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

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

12.04.2019, 16:53

8

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private string number;
        public string Number
        {
            set
            {
                if ((int.Parse(value) < 100000000000) && (int.Parse(value) >= 70000000000) && (int.Parse(value)/ 10000000000 == 7))
                {
                    number = value;
                }
 
                else
                {
                    throw new ArgumentException("Телефон должен быть введен корректно(начинаться с 7 и иметь длинну 11 цифр");
                }
 
            }
 
            get
            {
                return number;
            }



1



КОП

1123 / 794 / 219

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

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

12.04.2019, 16:56

9

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

Решение

Цитата
Сообщение от FuKs1k
Посмотреть сообщение

Куда мне int.parse() прописать?

там даже 1 знак не влезет, поэтому long

C#
1
if ((long.Parse(value) < 100000000000) && (long.Parse(value) >= 70000000000) && (long.Parse(value)/ 10000000000 == 7))

Цитата
Сообщение от FuKs1k
Посмотреть сообщение

Либо как сделать номер числом?

это было бы

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private long number;
        public long Number
        {
            set
            {
                if ((value < 100000000000) && (value >= 70000000000) && (value / 10000000000 == 7))
                {
                    number = value;
                }
 
                else
                {
                    throw new ArgumentException("Телефон должен быть введен корректно(начинаться с 7 и иметь длинну 11 цифр");
                }
 
            }
 
            get
            {
                return number;
            }



1



FuKs1k

0 / 0 / 0

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

Сообщений: 14

12.04.2019, 17:01

 [ТС]

10

Возникла другая ошибка CS0652 Сравнение с целочисленной константой не имеет смысла; константа находится вне диапазона значений типа «int».

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private string number;
        public string Number
        {
            set
            {
                if ((int.Parse(value) < 100000000000) && (int.Parse(value) >= 70000000000) && (int.Parse(value)/ 10000000000 == 7))
                {
                    number = value;
                }
 
                else
                {
                    throw new ArgumentException("Телефон должен быть введен корректно(начинаться с 7 и иметь длинну 11 цифр");
                }
 
            }
 
            get
            {
                return number;
            }
        }

Добавлено через 2 минуты
Спасибо большое, с long.parse сработало.



0



1346 / 835 / 419

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

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

12.04.2019, 17:01

11

Цитата
Сообщение от FuKs1k
Посмотреть сообщение

Возникла другая ошибка CS0652 Сравнение с целочисленной константой не имеет смысла; константа находится вне диапазона значений типа «int».

Вам сколько лет FuKs1k. Вам выше уже сказали что диапазон по типу Int не подходит нужно использовать long.



0



0 / 0 / 0

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

Сообщений: 14

12.04.2019, 17:05

 [ТС]

12

Лет мне 20, но в программирование я 0. Я сначала увидел ваш код его вставил у меня вышла такая ошибка, потом увидел уже про long.parse



0



Diamante

3396 / 2412 / 1161

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

Сообщений: 8,086

12.04.2019, 21:23

13

а зачем телефон хранить числом? проверку удобней сделать так

C#
1
2
3
4
            if (Regex.IsMatch(inputString, @"7w{10}"))
            {
                //подходит
            }



1



I have a Datalist in a ASP.NET page  which contains three labels.  One of the labels is a Numeric Value which is bound to a table column.  Basicly when a select button is pushed the value is decreased by a number of 1 and the result is shown in the next label.  This worked fine when I used it in VB however I need it for C# and im getting a strange error message,  
CS0019: Operator ‘-‘ cannot be applied to operands of type ‘string’ and ‘string’

Can somebody please assist me with this problem.

Compilation Error 
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 
 
Compiler Error Message: CS0019: Operator '-' cannot be applied to operands of type 'string' and 'string'
 
Source Error:
 
 
 
Line 27:                 <asp:LinkButton ID="LinkButton1" runat="server" 
Line 28:                     Text='<%# Eval("Date", "{0:D}") %>' onclick="LinkButton1_Click"></asp:LinkButton><br />
Line 29:                 <asp:Label ID="Label6" runat="server" Text='<%# Eval("Value1", "{0}") - Eval("[Total Notes]", "{0}") %>'></asp:Label>
Line 30:                 (
Line 31:                 <asp:Label ID="Label4" runat="server" Text='<%# Eval("Value1", "{0}") %>'></asp:Label>
 
 
Source File: c:inetpubTsaSiteMembershipAnnualLeaveSelectAnnualLeave.aspx    Line: 29

Open in new window

regemailforsites2

User
Posts: 25

Operator ‘??’ cannot be applied to operands of type ‘string

When I add any line of C# code that uses the ? conditional operator to Table->Table Options->General->Filter, I get the following error:

error CS0019: Operator ‘??’ cannot be applied to operands of type ‘string’ and ‘bool’

I even tried very intuitive cases like true? «»:»»

Any solution to this please?


MichaelG

User
Posts: 862

Post

by MichaelG » Tue Jul 07, 2020 8:03 am

Try enclosing with brackets, e.g (true ? «a» : «b»)


regemailforsites2

User
Posts: 25

Post

by regemailforsites2 » Tue Jul 07, 2020 3:08 pm

Thanks, it works now. The other Filter fields worked fine without the parentheses. Since this Filter field needs a special treatment, it’d be better if this gets documented in the help file.


Понравилась статья? Поделить с друзьями:
  • Error cs0019 operator cannot be applied to operands of type char and string
  • Error cs0019 operator cannot be applied to operands of type bool and int
  • Error cs0019 operator cannot be applied to operands of type bool and double
  • Error cs0006 не удалось найти файл метаданных microsoft vsa dll
  • Error cs0006 metadata file could not be found