Visual C # Language Concept-data type (C # and Java)

Source: Internet
Author: User
Visual C # Language concepts Data Type (C # and Java)

This topic discusses the main similarities and differences between Java and C # In data representation, allocation, and garbage collection.

Composite data type

In Java and C #, the concept of a class as a composite data type with fields, methods, and events is similar. (The concept of class inheritance is discussed separately in the topic titled inheritance and derived classes (C # and Java .) C # introduce the concept of structure. The structure is a type of composite data for stack allocation, which does not support inheritance. In many other aspects, the structure is very similar to the class. Structure provides a lightweight method that combines related fields and methods for use in compact loops and other performance-critical scenarios.

C # enables you to create a destructor method called before garbage collection of class instances. In Java, you can useFinalizeMethod to include code, used to clear resources before the object is recycled as garbage. In C #, this function is executed by class destructor. The Destructor is like no parameter and there is no prefix (~) Constructor.

Built-in Data Types

C # provides all data types available in Java and supports unsigned numbers and the New 128-bit high-precision floating point type.

The core Class Library provides a packaging class for each base metadata type in Java, which represents the base metadata type as a Java object. For example, Int32 class PackagingIntData Type: Double type, double type.

On the other hand, all base metadata types in C # Are objects in the System namespace. Each data type is abbreviated as (or alias ). For example,IntYesSystem. Int32AndDoubleYesSystem. Double.

The following table lists the C # data types and their aliases. As shown in the table, the first eight data types correspond to the primitive types available in Java. Note thatBooleanIn C #,Bool.

Abbreviation . NET class Type Width Range (BIT)

Byte

Byte

Unsigned integer

8

0 to 255

Sbyte

SByte

Signed integer

8

-128 to 127

Int

Int32

Signed integer

32

-2,147,483,648 to 2,147,483,647

Uint

UInt32

Unsigned integer

32

0 to 4294967295

Short

Int16

Signed integer

16

-32,768 to 32,767

Ushort

UInt16

Unsigned integer

16

0 to 65535

Long

Int64

Signed integer

64

-922337203685477508 to 922337203685477507

Ulong

UInt64

Unsigned integer

64

0 to 18446744073709551615

Float

Single

Single precision floating point type

32

-3.402823e38 to 3.402823e38

Double

Double

Dual-precision floating point

64

-1.79769313486232e308 to 1.79769313486232e308

Char

Char

Single Unicode Character

16

Unicode characters used in text

Bool

Boolean

Logical Boolean Type

8

True or False

Object

Object

Base types of all other types

String

String

Character Sequence

Decimal

Decimal

Exact decimal type or Integer type, which can represent the decimal number with 29 valid digits

128

± 1. 0 × 10e − 28 to ± 7. 9 × 10e28

Because C # treats all base metadata types as objects, you can call the object method on the base metadata type. For example:

C # copy code
static void Main()
{
int i = 10;
object o = i;
System.Console.WriteLine(o.ToString());
}

This operation is completed with automatic packing and unboxing. For more information, see packing and unboxing (C # programming guide ).

Constant

Both Java and C # can declare a variable whose value is specified during compilation and cannot be changed during runtime. JavaFinalThe field modifier declares such variables, while C # uses the const keyword. BesidesConstIn addition, C # also provides the readonly keyword to declare variables that can be assigned a value at runtime (in the declaration statement or in the constructor. After initialization,ReadonlyThe variable value cannot be changed. You can useReadonlyVariable. If module A is updated and A new version number is used for re-compilation, Module B can use this new constant value for initialization without re-compilation.

Enumeration

Enumeration is used to group named constants. It is similar to the usage in C and C ++, but cannot be used in Java. The following example defines a simpleColorEnumeration.

C # copy code
public enum Color
{
Green, //defaults to 0
Orange, //defaults to 1
Red, //defaults to 2
Blue //defaults to 3
}

You can also assign an integer to the enumeration, as shown in the following enumeration declaration:

C # copy code
public enum Color2
{
Green = 10,
Orange = 20,
Red = 30,
Blue = 40
}

The following code example calls the GetNames method of the Enum type to display the available constants of enumeration. Then, assign the value to the enumeration and display the value.

C # copy code
class TestEnums
{
static void Main()
{
System.Console.WriteLine("Possible color choices: ");

//Enum.GetNames returns a string array of named constants for the enum.
foreach(string s in System.Enum.GetNames(typeof(Color)))
{
System.Console.WriteLine(s);
}

Color favorite = Color.Blue;

System.Console.WriteLine("Favorite Color is {0}", favorite);
System.Console.WriteLine("Favorite Color value is {0}", (int) favorite);
}
}
Output

Possible color choices:

Green

Orange

Red

Blue

Favorite Color is Blue

Favorite Color value is 3

String

Java
And C #
The behavior of the string type in is similar, with only minor differences. The two string types are unchangeable, meaning that once a string is created, the value of the string cannot be changed. The methods in the two instances seem to have been modified.
The actual content of the string is actually created and a new string is returned, while the original string remains unchanged. The process of comparing string values in C # and Java is different. To
To compare the string value, the developer needs to callEqualsThe reason is that, by default=The operator compares the reference type. In C #, developers can directly use=Or! =To compare string values. Although the string in C # is of the reference type=And! =The operator compares string values rather than references.

Like in Java, C # developers should not concatenate strings using string types to avoid the overhead of creating a new string class each time a string is concatenated. On the contrary, developers can use the StringBuilder class, which is similar toStringBufferClass is functionally equivalent.

String text

C # Avoid using escape sequences in string constants, such as "\ t" for tabs or "\" for backslash characters "\". To achieve this, you only need to use the @ symbol to declare the original string before assigning the string value. The following example shows how to use escape characters and how to allocate string text:

C # copy code
static void Main()
{
//Using escaped characters:
string path1 = "\\\\FileShare\\Directory\\file.txt";
System.Console.WriteLine(path1);

//Using String Literals:
string path2 = @"\\FileShare\Directory\file.txt";
System.Console.WriteLine(path2);
}
Conversion and forced conversion

Java and C # follow similar rules for automatic conversion and forced conversion of data types.

Like Java, C # supports implicit and explicit conversions. If the conversion is extended, it is implicit conversion. For exampleIntToLongTo implicit conversion, the same as in Java:

C # copy code
int int1 = 5;
long long1 = int1; //implicit conversion

The following is a list of implicit conversions between. NET Framework data types:

Source Type Target type

Byte

Short, ushort, int, uint, long, ulong, float, double, or decimal

Sbyte

Short, int, long, float, double, or decimal

Int

Long, float, double, or decimal

Uint

Long, ulong, float, double, or decimal

Short

Int, long, float, double, or decimal

Ushort

Int, uint, long, ulong, float, double, or decimal

Long

Float, double, or decimal

Ulong

Float, double, or decimal

Float

Double

Char

Ushort, int, uint, long, ulong, float, double, or decimal

Use the same syntax as Java to forcibly convert the expression to be explicitly converted:

C # copy code
long long2 = 5483;
int int2 = (int)long2; //explicit conversion

The following table lists the Explicit conversions.

Source Type Target type

Byte

Sbyte or char

Sbyte

Byte, ushort, uint, ulong, or char

Int

Sbyte, byte, short, ushort, uint, ulong, or char

Uint

Sbyte, byte, short, ushort, int or char

Short

Sbyte, byte, ushort, uint, ulong, or char

Ushort

Sbyte, byte, short, or char

Long

Sbyte, byte, short, ushort, int, uint, ulong, or char

Ulong

Sbyte, byte, short, ushort, int, uint, long, or char

Float

Sbyte, byte, short, ushort, int, uint, long, ulong, char, or decimal

Double

Sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or decimal

Char

Sbyte, byte, or short

Decimal

Sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or double

Value and reference type

C # two types of variables are supported:

  • Value Type

    These are built-in base metadata types (such as char, int, and float) and user-defined types declared with struct.

  • Reference Type

    Classes constructed from primitive types and other complex data types. This type of variable does not include the type of instance but only references to the instance.

If you create two value type variables I and j (as shown below), I and j are completely independent of each other:

C # copy code
int i = 10;
int j = 20;

Specify independent memory locations for them:

If you change the values of one of these two variables, the other variables will not be affected. For example, if there is an expression in the following form, there is still no association between the two variables:

C # copy code
int k = i;

That is, if you change the value of I, k retains the value that I has when the value is assigned.

C # copy code
i = 30;

System.Console.WriteLine(i.ToString()); // 30
System.Console.WriteLine(k.ToString()); // 10

However, the action of the reference type is different. For example, you can declare two variables as follows:

C # copy code
Employee ee1 = new Employee();
Employee ee2 = ee1;

Now, because the class in C # is of the reference typeEe1Is considered to beEmployee. In the first two lines, the first line is created in the memoryEmployeeAnd setEe1To reference the instance. ThereforeEe2Set to equalEe1It contains repeated references to classes in the memory. If you changeEe2, ThenEe1The attributes on will reflect these changes, because both point to the same object in the memory, as shown below:

Packing and unboxing

The process of converting a value type to a reference type is called packing. Otherwise, the process of converting the reference type to the value type is called unboxing. The following code illustrates this:

C # copy code
int i = 123;      // a value type
object o = i; // boxing
int j = (int)o; // unboxing

Java requires manual execution of this type of conversion. You can convert the base metadata type to the packaging class object by constructing such an object or packing it. Similarly, you can extract the value of the base metadata type from the packaging class object by calling the appropriate method or unboxing the object. For more information about packing and unboxing, see packing conversion (C # Programming Guide) and canceling packing conversion (C # programming guide ).

See references

Data Type (C # programming guide)
Concept

C # programming guide
Other resources

Visual C #
C # programming language (for Java developers)

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.