C # basic knowledge (5). variable types and string processing

Source: Internet
Author: User
Tags float double naming convention

This article is written by Karli Watson. it mainly includes some of your lack of C # basic knowledge and online note usage, this article mainly covers C # simple variable types and complex variable types, naming rules, implicit conversion and display conversion, variable string processing, and so on. It is a very basic knowledge and is helpful for beginners.

I. C # simple variable types and naming rules

Simple types constitute the basic component types in the application, which mainly include the following types:

Integer type

Sbyte (-128 ~ Integer between 127) byte (0 ~ Integer between 255)Short (-32768 ~ Integer between 32767)
Ushort (0 ~ Integer between 65535)
INT (4 bytes, 1 byte = 8bit) uint (0 ~ 2 ^ integer between 32-1)
Long (alias: system. int64)
Ulong (alias: system. uint64, U is short for unsigned, non-negative)

Floating Point Type

Float double (+/-M * 2 ^ e) decimal (+/-M * 10 ^ e)

Three simple types

Char (a Unicode character, store 0 ~ Integer between 65535)
Bool (Boolean value true/false) string (a group of characters)

C # variable naming rules: the first character of a variable name must be a letter, underscore (_), or @, followed by letters, underscores, or numbers.
Naming Convention: In the past, we used Hungarian notation to add a lowercase prefix to the variable name to indicate its type, such as int type iage. but since C #. net Framework type is complex, it is best to name them according to the role of variables, currently. net Framework naming conventions: pascalcase and camelcase. the names are case-sensitive and contain multiple words.
Pascalcase
Specify that each word in the name contains only the first letter and the other lowercase letters, such as age/lastname/winterofdiscontent.
The first word in camelcase starts with a lowercase letter, such as age, firstname, and timeofdeath. microsoft recommends that you use the camelcase rule for simple variables and pascalcase for advanced naming. we recommend that you try to use this method when naming it for your convenience.
Note: words such as month_time in the variable name of the underline character segmentation have been eliminated.
Character string: All characters between two double quotes are included in the string, including the last line character and escape character. the only exception is that the Escape Character of double quotation marks must be specified to avoid ending the string. You can add @.
The specified string is very useful (backslash character \) in the file name. The previous project involves the disk directory and image path. It can be seen that it is widely used. that is, @ "C: \ temp \ mydir \ myfile.doc" = "C: \ temp \ mydir \ myfile.doc ".
Bitwise operations include & bitwise AND | bitwise OR ^ bitwise OR ~ Reverse <left shift> right shift.

Ii. implicit conversion and display Conversion

Implicit conversion: the conversion from type A to type B can be performed in all cases. The conversion rule is simple and allows the compiler to execute the conversion.
Display conversion: the conversion from type A to type B can only be performed in some cases. The conversion rules are complex and should be processed by some type.
The implicit conversion rule is that the value range of type A is completely included in the value range of type B, and can be converted to type B. here, byte can be converted to short/INT or float and can be converted to double. short Type variables can be stored 0 ~ 32767 while byte can store a maximum value of 255. Therefore, when short converts byte ~ Error 32767.
Explicit conversion explicitly requires the compiler to convert a value from one data type to another. The format of code writing varies with the conversion method. it is equivalent to "I already know that you have warned me about this, but I will be responsible for the consequences ". for example:
Byte n; short M = 7; n = m;
It will report an error: the type "short" cannot be implicitly converted to "Byte", there is a display conversion (is there a lack of forced conversion ?)
The short variable must be forcibly converted to byte, for example, n = (byte) M. Note that data loss occurs when m is greater than 255.
C # provide expression overflow check context. Use the checked and unchecked keywords, such as N = checked (byte) M). When M = 281, an error message "arithmetic operation causes overflow" is reported ".
PS: the provisioning expressions contain checked. Right-click solution Resource Manager and choose Project> Properties> Generate> advanced) -> select "check operation overflow/underflow", as shown in:

Another display conversion method is to use the convert command for display conversion. to convert to int, use convert. toint32 (); convert to a string using convert. tostring (boolval); the result outputs "True/false ". this is often used when I use strings and set encoding formats.

3. complex variable types: enumerated Array

Complex Variable types include:
Enumeration: variable type. You can define a set of possible discrete values. These values are used in an understandable way.
Structure: The type of the merged variable, which is composed of a group of other variable types defined by the user.
Array: contains multiple variables of one type. Each value can be accessed through an index.
1. Enumeration
Sometimes you want the variable to propose a value in a fixed set, for example, week storage 7 days a week, and month storage 12 months. enumeration allows defining a type, which contains a value in the provided limit value set. For example, enumeration type orientation can store North/South/East/West values. the default Enumeration type is int. By default, each value is automatically assigned to the corresponding basic type according to the defined order (starting from 0. if no value is assigned, an initial value is automatically obtained. The value is greater than the value explicitly stated above. example:

Namespace test {// defines the enumeration type and specifies the actual Enum orientation of each enumeration: byte {North = 1, South = 2, East = 3, west = 4} class program {static void main (string [] ARGs) {// declare the enumerated type variable orientation mydirection = orientation. south; console. writeline ("mydirection = {0} {1}", mydirection, (INT) mydirection); console. readkey ();}}}

PS: the output result of this program is "mydirection = South 2". In actual projects, enumeration applications, such as the userselect variable of the enumeration type, are customized when the drawing software is created, then judge its if (iuserselect = (INT) userselect. select) the mouse selects line segments, rectangles, and selected States. in C language, the assignment of enumeration types, comparison of occupied space addresses and structures are often investigated.
2. Structure
Struct, short for structure. A structure is a data structure composed of several data types. you can define your own variable types based on this structure. for example, if the student information (student ID + name) and stored for a certain distance (Direction + distance), it is assumed that the four directions are southeast and northwest. the general method is to define: Orientation mydirection; double mydistance; but it is difficult to define variables when multiple paths are stored, so the structure struct is introduced. it mainly includes struct data members in the format of "<accessibility> <type> <Name>; Modify type name ". example:

Namespace test {// defines the enumeration type and specifies the actual Enum orientation value for each enumeration: byte {north, south, east, west} // defines the structure type struct route {public orientation ction; // public double distance; // DISTANCE} class program {static void main (string [] ARGs) {// define structure type variables and assign values to route myroute; myroute. direction = orientation. west; myroute. distance = 3.14; console. writeline ("direction = {0} distance = {1}", myroute. direction, myroute. distance); console. readkey ();}}}

The running result is "direction = West distance = 3.14 ".
3. Array
An array is the index list of a variable. It is stored in an array type variable and multiple values of the same type are stored. unlike C, C # declares an array using the following methods: <basetype> [] <Name> For example: int [] myarray;

Two Methods for initialization:
Int [] myarray = {1, 2, 3, 4, 5}; or Int [] myarray = new int [5];
New indicates that the size of the initialized array is 5, and the default value is 0 for the array element. such as console. writeline ("aarray = {0}, barray = {1}", aarray [3], barray [2]); output number "aarray = 4, barray = 0 ". the array index starts from 0 and is defined as name [5], that is, the index is 0-4. declaration of multi-dimensional arrays, such as double [,] length = new double [3, 4], indicates an array of 3*4. these basic knowledge will not be emphasized.

Iv. string processing

<String>. tochararray () gets a writable char array that stores all the characters of the current string and copies the string to the specified character array. for example: String STR = "this is a string"; char [] CHS = Str. tochararray ();
<String>. Length: gets the number of elements and returns the number of characters in the string.
<String>. tolower | <string>. toupper () converts a string to lowercase or upper-case, which is used for comparison or assignment, for example, if (useresponse. tolower () = "yes ").
<String>. trim () removes spaces from the beginning and end of the input string. for example, char [] CHS = {'', 'E', 's'}; string STR =" This Is A Yeeees "; STR = Str. trim (CHS); output "this is a Y ". remove all spaces, letters E, and s from the front or back of the string, while the spaces \ e \ s remain unchanged.
<String>. trimstart () | <string>. trimend () removes spaces before or after the string.
<String>. padleft () | <string>. add spaces to the left or right side of the padright () string so that the string reaches the specified length. this method is used to align strings in columns. It is often used for database query and display information. for example, STR = "abcdefg"; STR = Str. padleft (10); // output "abcdefg" str = Str. padright (10, 'x'); // output "abcdefgxxx ".
<String>. Split () converts a string to a string array. It is separated at the specified position and the separator is deleted. The following uses spaces to separate string STR = "this is a string! "Char [] CHS = {''}; string [] words; words = Str. Split (CHS); // output this is a string! Four words
PS: there are still many character string processing functions that are not continued by the author. When you can enter the first character of the Code, IDE helps you to provide the input keywords, variable names, type names, etc, that is, the intelliisense function (smart sensing ). in addition, when querying usage and keywords, you can press Ctrl to continue reading the blocked part of the code (transparent ). this CTRL is also known in the books.
Summary:
This article focuses on the basic knowledge of C # variable types and string processing. For more information, see C # Getting Started classic. We recommend that you learn C # Getting Started books. sometimes I think a lot about writing this article, and it may be a bit watery, but I have a clear conscience. in fact, I am more willing to write some things about the actual project or some real technical articles about the project. However, due to my lack of experience and general project capabilities, I still need to continue to study and practice, this basic article is mostly online notes! Sometimes it seems a little sad. I hope that I can learn something and do something with my mind in the future. But now I am always confused. I feel a lot of things need to be learned and weak, no matter what, learn something in a down-to-earth Manner, immerse yourself in the code, and find your own way of life! Encourage yourself,If you have any errors or deficiencies, please try again! You can also share suggestions or instructions ~
(By: eastmount original csdn http://blog.csdn.net/eastmount)

C # basic knowledge (5). variable types and string processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.