Csharp/CSharp Tutorial/Data Type/Data Type

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

bool: False/True string

<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
   Console.WriteLine("bool.FalseString: {0}",bool.FalseString);
   Console.WriteLine("bool.TrueString: {0}",bool.TrueString);
   }

}</source>

bool.FalseString: False
bool.TrueString: True

Converting Numeric Strings to Their Internal Representation

For the numeric types, the .NET structure names and their C# keyword equivalents are shown here:

.NET Structure Name C# Name Decimal decimal Double double Single float Int16 short Int32 int Int64 long UInt16 ushort UInt32 uint UInt64 ulong Byte byte Sbyte sbyte

  1. The structures are defined inside the System namespace.
  2. The fully qualified name for Int32 is System.Int32.

Convert numeric types explicit to "smaller" types

<source lang="csharp">class MainClass {

   public static void Main()
   {
       // all implicit
       sbyte v = 55;
       short v2 = v;
       int v3 = v2;
       long v4 = v3;
       
       // explicit to "smaller" types
       v3 = (int) v4;
       v2 = (short) v3;
       v = (sbyte) v2;
   }

}</source>

C#"s Value Types

C# contains two general categories of built-in data types:

  1. value types
  2. reference types.

C#"s reference types are defined by classes.

2.1.Data Type 2.1.1. C#"s Value Types 2.1.2. <A href="/Tutorial/CSharp/0040__Data-Type/TheCValueTypes.htm">The C# Value Types </a> 2.1.3. <A href="/Tutorial/CSharp/0040__Data-Type/ConvertingNumericStringstoTheirInternalRepresentation.htm">Converting Numeric Strings to Their Internal Representation</a> 2.1.4. <A href="/Tutorial/CSharp/0040__Data-Type/Literals.htm">Literals</a> 2.1.5. <A href="/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm">Primitives in C#</a> 2.1.6. <A href="/Tutorial/CSharp/0040__Data-Type/SystemTypesandCShorthand.htm">System Types and C# Shorthand</a> 2.1.7. <A href="/Tutorial/CSharp/0040__Data-Type/Datatypedefaultvalue.htm">Data type default value</a> 2.1.8. <A href="/Tutorial/CSharp/0040__Data-Type/Thedifferencesbetweenintanddouble.htm">The differences between int and double.</a> 2.1.9. <A href="/Tutorial/CSharp/0040__Data-Type/Explicitnumericconversions.htm">Explicit numeric conversions</a> 2.1.10. <A href="/Tutorial/CSharp/0040__Data-Type/Convertnumerictypesexplicittosmallertypes.htm">Convert numeric types explicit to "smaller" types</a> 2.1.11. <A href="/Tutorial/CSharp/0040__Data-Type/SystemInt32value.htm">System.Int32 value</a> 2.1.12. <A href="/Tutorial/CSharp/0040__Data-Type/UInt16MaxValueMinValue.htm">UInt16.MaxValue/MinValue</a> 2.1.13. <A href="/Tutorial/CSharp/0040__Data-Type/SystemUInt16value.htm">System.UInt16 value</a> 2.1.14. <A href="/Tutorial/CSharp/0040__Data-Type/boolFalseTruestring.htm">bool: False/True string</a> 2.1.15. <A href="/Tutorial/CSharp/0040__Data-Type/ulongMaxMinvalue.htm">ulong: Max/Min value</a> 2.1.16. <A href="/Tutorial/CSharp/0040__Data-Type/Parsingstringstocreatedatatypes.htm">Parsing strings to create data types</a> 2.1.17. <A href="/Tutorial/CSharp/0040__Data-Type/Parsingstringstocreatedatatypesint.htm">Parsing strings to create data types: int</a> 2.1.18. <A href="/Tutorial/CSharp/0040__Data-Type/Parsingstringstocreatedatatypeschar.htm">Parsing strings to create data types: char</a> 2.1.19. <A href="/Tutorial/CSharp/0040__Data-Type/CTSTypesandAliases.htm">CTS Types and Aliases</a> 2.1.20. <A href="/Tutorial/CSharp/0040__Data-Type/SpecifyingLiteralValues.htm">Specifying Literal Values</a> 2.1.21. <A href="/Tutorial/CSharp/0040__Data-Type/DatatypeFunctionality.htm">Data type Functionality</a> 2.1.22. <A href="/Tutorial/CSharp/0040__Data-Type/Defaultvaluesforprimitivetypes.htm">Default values for primitive types</a> 2.1.23. <A href="/Tutorial/CSharp/0040__Data-Type/DataDeclarations.htm">Data Declarations</a> 2.1.24. <A href="/Tutorial/CSharp/0040__Data-Type/Usingnewtocreateintrinsicdatatypes.htm">Using new to create intrinsic data types</a> 2.1.25. <A href="/Tutorial/CSharp/0040__Data-Type/DefaultValueComparison.htm">Default Value Comparison</a>

CTS Types and Aliases

<source lang="csharp">CTS Type Name C# Alias Description System.Object Object Base class for all CTS types System.String String String System.Sbyte Sbyte Signed 8-bit byte System.Byte Byte Unsigned 8-bit byte System.Int16 Short Signed 16-bit value System.UInt16 Ushort Unsigned 16-bit value System.Int32 Int Signed 32-bit value System.UInt32 Uint Unsigned 32-bit value System.Int64 Long Signed 64-bit value System.UInt64 Ulong Unsigned 64-bit value System.Char Char 16-bit Unicode character System.Single Float IEEE 32-bit float System.Double Double IEEE 64-bit float System.Boolean Bool Boolean value (true/false) System.Decimal Decimal 128-bit data type</source>

Data Declarations

<source lang="csharp">using System; using System.Collections.Generic; using System.Text;

 class Program
 {
   static void Main(string[] args)
   {
     // Local variables are declared and initialized as so:
     // dataType varName = initialValue;
     int myInt = 0;
     string myString;
     myString = "This is my character data";
     // Declare 3 bools on a single line.
     bool b1 = true, b2 = false, b3 = b1;
     System.Boolean b4 = false;
     System.Console.WriteLine("Your data: {0}, {1}, {2}, {3}, {4}, {5}",
         myInt, myString, b1, b2, b3, b4);
   }
 }</source>

Data type default value

<source lang="csharp">using System; class MainClass {

 public sbyte  theSignedByte;
 public byte    theByte;
 public short  theShort;
 public ushort  theUShort;
 public int    theInt;
 public uint    theUInt;
 public long    theLong;
 public ulong  theULong;
 public char    theChar;
 public float  theFloat;
 public double  theDouble;
 public bool    theBool;
 public decimal  theDecimal;
 public string  theStr;
 public object  theObj;
 public static int Main(string[] args)
 {
   MainClass v = new MainClass();
   Console.WriteLine("bool: {0}", v.theBool);
   Console.WriteLine("byte: {0}", v.theByte);
   Console.WriteLine("char: {0}", v.theChar);
   Console.WriteLine("decimal: {0}", v.theDecimal);
   Console.WriteLine("double: {0}", v.theDouble);
   Console.WriteLine("float: {0}", v.theFloat);
   Console.WriteLine("int: {0}", v.theInt);
   Console.WriteLine("long: {0}", v.theLong);
   Console.WriteLine("object: {0}", v.theObj);
   Console.WriteLine("short: {0}", v.theShort);
   Console.WriteLine("signed byte: {0}", v.theSignedByte);
   Console.WriteLine("string: {0}", v.theStr);
   Console.WriteLine("unsigned int: {0}", v.theUInt);
   Console.WriteLine("unsigned long: {0}", v.theULong);
   Console.WriteLine("unsigned short: {0}", v.theUShort);
   return 0;
 }

}</source>

bool: False
byte: 0
char:
decimal: 0
double: 0
float: 0
int: 0
long: 0
object:
short: 0
signed byte: 0
string:
unsigned int: 0
unsigned long: 0
unsigned short: 0

Data type Functionality

<source lang="csharp">using System; using System.Collections.Generic; using System.Text;

 class Program
 {
   static void Main(string[] args)
   {
     Console.WriteLine("Max of int: {0}", int.MaxValue);
     Console.WriteLine("Min of int: {0}", int.MinValue);
     Console.WriteLine("Max of double: {0}", double.MaxValue);
     Console.WriteLine("Min of double: {0}", double.MinValue);
     Console.WriteLine("double.Epsilon: {0}", double.Epsilon);
     Console.WriteLine("double.PositiveInfinity: {0}",double.PositiveInfinity);
     Console.WriteLine("double.NegativeInfinity: {0}",double.NegativeInfinity);
     Console.WriteLine("bool.FalseString: {0}", bool.FalseString);
     Console.WriteLine("bool.TrueString: {0}", bool.TrueString);
   }
 }</source>

Default Value Comparison

<source lang="csharp">using System; using System.ruponentModel;

   class DefaultValueComparison
   {
       static int CompareToDefault<T>(T value)
           where T : IComparable<T>
       {
           return value.rupareTo(default(T));
       }
   
       static void Main()
       {
           Console.WriteLine(CompareToDefault("x"));
           Console.WriteLine(CompareToDefault(10));
           Console.WriteLine(CompareToDefault(0));
           Console.WriteLine(CompareToDefault(-10));
           Console.WriteLine(CompareToDefault(DateTime.MinValue));
       }
   }</source>

Default values for primitive types

<source lang="csharp">Type Default value Reference null Numeric type or Enum type 0 char type "\0" bool type false</source>

Explicit numeric conversions

<source lang="csharp">using System; class MainClass {

   public static void Main()
   {
       uint value1 = 312;
       byte value2 = (byte) value1;
       Console.WriteLine("Value2: {0}", value2);
   }

}</source>

Value2: 56

Literals

literals refer to fixed values that are represented in their human-readable form.

  1. To specify a long literal, append an l or an L. For example, 12 is an int, but 12L is a long.
  2. To specify an unsigned integer value, append a u or U. Thus, 100 is an int, but 100U is a uint.
  3. To specify an unsigned, long integer, use ul or UL. For example, 984375UL is of type ulong.
  4. To specify a float literal, append an F or f to the constant. For example, 10.19F is of type float.
  5. To specify a decimal literal, follow its value with an m or M. For example, 9.95M is a decimal literal.
  6. A hexadecimal literal must begin with 0x (a zero followed by an x).

2.1.Data Type 2.1.1. <A href="/Tutorial/CSharp/0040__Data-Type/CsValueTypes.htm">C#"s Value Types</a> 2.1.2. <A href="/Tutorial/CSharp/0040__Data-Type/TheCValueTypes.htm">The C# Value Types </a> 2.1.3. <A href="/Tutorial/CSharp/0040__Data-Type/ConvertingNumericStringstoTheirInternalRepresentation.htm">Converting Numeric Strings to Their Internal Representation</a> 2.1.4. Literals 2.1.5. <A href="/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm">Primitives in C#</a> 2.1.6. <A href="/Tutorial/CSharp/0040__Data-Type/SystemTypesandCShorthand.htm">System Types and C# Shorthand</a> 2.1.7. <A href="/Tutorial/CSharp/0040__Data-Type/Datatypedefaultvalue.htm">Data type default value</a> 2.1.8. <A href="/Tutorial/CSharp/0040__Data-Type/Thedifferencesbetweenintanddouble.htm">The differences between int and double.</a> 2.1.9. <A href="/Tutorial/CSharp/0040__Data-Type/Explicitnumericconversions.htm">Explicit numeric conversions</a> 2.1.10. <A href="/Tutorial/CSharp/0040__Data-Type/Convertnumerictypesexplicittosmallertypes.htm">Convert numeric types explicit to "smaller" types</a> 2.1.11. <A href="/Tutorial/CSharp/0040__Data-Type/SystemInt32value.htm">System.Int32 value</a> 2.1.12. <A href="/Tutorial/CSharp/0040__Data-Type/UInt16MaxValueMinValue.htm">UInt16.MaxValue/MinValue</a> 2.1.13. <A href="/Tutorial/CSharp/0040__Data-Type/SystemUInt16value.htm">System.UInt16 value</a> 2.1.14. <A href="/Tutorial/CSharp/0040__Data-Type/boolFalseTruestring.htm">bool: False/True string</a> 2.1.15. <A href="/Tutorial/CSharp/0040__Data-Type/ulongMaxMinvalue.htm">ulong: Max/Min value</a> 2.1.16. <A href="/Tutorial/CSharp/0040__Data-Type/Parsingstringstocreatedatatypes.htm">Parsing strings to create data types</a> 2.1.17. <A href="/Tutorial/CSharp/0040__Data-Type/Parsingstringstocreatedatatypesint.htm">Parsing strings to create data types: int</a> 2.1.18. <A href="/Tutorial/CSharp/0040__Data-Type/Parsingstringstocreatedatatypeschar.htm">Parsing strings to create data types: char</a> 2.1.19. <A href="/Tutorial/CSharp/0040__Data-Type/CTSTypesandAliases.htm">CTS Types and Aliases</a> 2.1.20. <A href="/Tutorial/CSharp/0040__Data-Type/SpecifyingLiteralValues.htm">Specifying Literal Values</a> 2.1.21. <A href="/Tutorial/CSharp/0040__Data-Type/DatatypeFunctionality.htm">Data type Functionality</a> 2.1.22. <A href="/Tutorial/CSharp/0040__Data-Type/Defaultvaluesforprimitivetypes.htm">Default values for primitive types</a> 2.1.23. <A href="/Tutorial/CSharp/0040__Data-Type/DataDeclarations.htm">Data Declarations</a> 2.1.24. <A href="/Tutorial/CSharp/0040__Data-Type/Usingnewtocreateintrinsicdatatypes.htm">Using new to create intrinsic data types</a> 2.1.25. <A href="/Tutorial/CSharp/0040__Data-Type/DefaultValueComparison.htm">Default Value Comparison</a>

Parsing strings to create data types

Structure Conversion Method Decimal static decimal Parse(string str) Double static double Parse(string str) Single static float Parse(string str) Int64 static long Parse(string str) Int32 static int Parse(string str) Int16 static short Parse(string str) UInt64 static ulong Parse(string str) UInt32 static uint Parse(string str) UInt16 static ushort Parse(string str) Byte static byte Parse(string str) SByte static sbyte Parse(string str)


<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
   bool myBool = bool.Parse("True");
   Console.WriteLine("-> Value of myBool: {0}", myBool);
   }

}</source>

Parsing strings to create data types: char

<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
   char myChar = char.Parse("w");
   Console.WriteLine("-> Value of myChar: {0}\n", myChar);
   }

}</source>

-> Value of myChar: w

Parsing strings to create data types: int

<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
   int myInt = int.Parse("8");
   Console.WriteLine("-> Value of myInt: {0}", myInt);
   }

}</source>

-> Value of myInt: 8

Primitives in C#

<source lang="csharp">Type Primitive Description Range bool System.Boolean Boolean true or false byte System.Byte 8-bit integer 0 to 255 char System.Char 16-bit Unicode character /u0000 to /uffff decimal System.Decimal 128-bit decimal (+/-)1.0 � 10^-28 to (+/-)7.9 � 10^28, with 28 to 29 digits of precision double System.Double 64-bit floating point -1.79769313486232e308 to 1.79769313486232e308 float System.Single 32-bit floating point (+/-)1.5 � 10^-45 to (+/-)3.4 � 10^38, with 7 digits of precision int System.Int32 32-bit unsigned integer -2,147,483,648 to 2,147,483,647 long System.Int64 64-bit integer -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 sbyte System.SByte 8-bit integer -128 to 127 short System.Int16 16-bit integer -32,768 to 32,767 string System.String not applicable String is an immutable variable length string. uint System.UInt32 32-bit unsigned integer 0 to 4,294,967,295 ulong System.UInt64 64-bit unsigned integer 0 to 18,446,744,073,709,551,615 ushort System.UInt16 16-bit unsigned integer 0 to 65,535</source>

Specifying Literal Values

<source lang="csharp">class MainClass {

 static void Main()
 {
   System.Console.WriteLine(42);
   System.Console.WriteLine(1.618034);
 }

}</source>

System.Int32 value

<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
   System.Int32 intA = 1001;
   System.Int32 intB = 1000;
   
   if(intA == intB)
     Console.WriteLine("Same value!\n");
   else
     Console.WriteLine("Not the same value!\n");
   }

}</source>

Not the same value!

System Types and C# Shorthand

<source lang="csharp">C# Shorthand CLS Compliant? System Type Range Meaning in Life sbyte No System.SByte 128 to 127 Signed 8-bit number byte Yes System.Byte 0 to 255 Unsigned 8-bit number short Yes System.Int16 32,768 to 32,767 Signed 16-bit number ushort No System.UInt16 0 to 65,535 Unsigned 16-bit number int Yes System.Int32 2,147,483,648 to 2,147,483,647 Signed 32-bit number uint No System.UInt32 0 to 4,294,967,295 Unsigned 32-bit number long Yes System.Int64 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Signed 64-bit number ulong No System.UInt64 0 to 18,446,744,073,709,551,615 Unsigned 64-bit number char Yes System.Char U0000 to Uffff A single 16-bit Unicode character float Yes System.Single 1.5 * 10^-45 to 3.4 * 10^38 32-bit floating point number double Yes System.Double 5.0 * 10^-324 to 1.7 * 10^308 64-bit floating point number bool Yes System.Boolean true or false Represents truth or falsity decimal Yes System.Decimal 10^0 to 10^28 A 96-bit signed number string Yes System.String Limited by system memory Represents a set of Unicode characters object Yes System.Object Any type can be stored in an object variable The base class of all types in the .NET universe</source>

System.UInt16 value

<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
   System.UInt16 myUInt16 = 30000;
   Console.WriteLine("Your value is: {0}", myUInt16.ToString());
   Console.WriteLine("I am a: {0}", myUInt16.GetType().ToString());
   }

}</source>

Your value is: 30000
I am a: System.UInt16

The C# Value Types

Type Meaning bool Represents true/false values byte 8-bit unsigned integer char Character decimal Numeric type for financial calculations double Double-precision floating point float Single-precision floating point int Integer long Long integer sbyte 8-bit signed integer short Short integer uint An unsigned integer ulong An unsigned long integer ushort An unsigned short integer

The differences between int and double.

<source lang="csharp">using System;

class MainClass {

 public static void Main() {  
   int ivar;     // an int variable 
   double dvar;  // a floating-point variable 

   ivar = 100;   // assign ivar the value 100 
   
   dvar = 100.0; // assign dvar the value 100.0 

   Console.WriteLine("Original value of ivar: " + ivar); 
   Console.WriteLine("Original value of dvar: " + dvar); 

   Console.WriteLine();            // print a blank line 

   // now, divide both by 3 
   ivar = ivar / 3;  
   dvar = dvar / 3.0; 

   Console.WriteLine("ivar after division: " + ivar); 
   Console.WriteLine("dvar after division: " + dvar); 
 }  

}</source>

Original value of ivar: 100
Original value of dvar: 100
ivar after division: 33
dvar after division: 33.3333333333333

UInt16.MaxValue/MinValue

<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
   Console.WriteLine("Max for an UInt16 is: {0}", UInt16.MaxValue);
   Console.WriteLine("Min for an UInt16 is: {0}", UInt16.MinValue);
   }

}</source>

Max for an UInt16 is: 65535
Min for an UInt16 is: 0

ulong: Max/Min value

<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
   Console.WriteLine("-> ulong.MaxValue: {0}",ulong.MaxValue);
   Console.WriteLine("-> ulong.MinValue: {0}\n",ulong.MinValue);
   }

}</source>

-> ulong.MaxValue: 18446744073709551615
-> ulong.MinValue: 0

Using new to create intrinsic data types

<source lang="csharp">using System; using System.Collections.Generic; using System.Text;

 class Program
 {
   static void Main(string[] args)
   {
     bool b = new bool();            // set to false.
     int i = new int();              // set to 0.
     double d = new double();        // set to 0.0.
     DateTime dt = new DateTime();   // set to 1/1/0001 12:00:00 AM
     Console.WriteLine("{0}, {1}, {2}, {3}",b, i, d, dt);
   }
 }</source>