Home > Backend Development > C#.Net Tutorial > String literals vs. string objects in C#

String literals vs. string objects in C#

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-09-06 17:45:07
forward
1027 people have browsed it

C# 中的字符串文字与字符串对象

String literals

String literals or constants are enclosed in double quotes "" or @"". Strings contain characters similar to character literals: plain characters, escape sequences, and universal characters.

The following are some examples of string literals -

Hello, World"
"Welcome, \
Copy after login

The following are examples showing the usage of string literals -

Example

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {

         // string
         string str1 ="Hello, World";
         Console.WriteLine(str1);

         // Multi-line string
         string str2 = @"Welcome,
         Hope you are doing great!";

         Console.WriteLine(str2);
      }
   }
}
Copy after login

String Object

Create a string object using one of the following methods -

  • By assigning a string literal to a string variable
  • By using the String class constructor
  • By using the string concatenation operator ( )
  • By retrieving a property or calling a method that returns a string
  • Convert a value or object to its string representation by calling a formatting method

Here's how to create a string object and compare two strings -

Example

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {
         string str1 = "John";
         string str2 = "Andy";

         if (String.Compare(str1, str2) == 0) {
            Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
         } else {
            Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
         }
         Console.ReadKey() ;
      }
   }
}
Copy after login

The above is the detailed content of String literals vs. string objects in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template