달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2016. 12. 29. 21:21

C# Keywords - Types 프로그래밍/C#2016. 12. 29. 21:21


Types


https://msdn.microsoft.com/en-us/library/3ewxz6et.aspx






Value Types


https://msdn.microsoft.com/en-us/library/s1ax56ch.aspx




bool


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The bool keyword is an alias of System.Boolean. It is used to declare variables to store the Boolean values, true and false.

System_CAPS_ICON_note.jpg Note

If you require a Boolean variable that can also have a value of null, use bool?. For more information, see Nullable Types.

You can assign a Boolean value to a bool variable. You can also assign an expression that evaluates to bool to a bool variable.

    public class BoolTest
    {
        static void Main()
        {
            bool b = true;

            // WriteLine automatically converts the value of b to text.
            Console.WriteLine(b);

            int days = DateTime.Now.DayOfYear;


            // Assign the result of a boolean expression to b.
            b = (days % 2 == 0);

            // Branch depending on whether b is true or false.
            if (b)
            {
                Console.WriteLine("days is an even number");
            }
            else
            {
                Console.WriteLine("days is an odd number");
            }   
        }
    }
    /* Output:
      True
      days is an <even/odd> number
    */

The default value of a bool variable is false. The default value of a bool? variable is null.

In C++, a value of type bool can be converted to a value of type int; in other words, false is equivalent to zero and true is equivalent to nonzero values. In C#, there is no conversion between the bool type and other types. For example, the following if statement is invalid in C#:

            int x = 123;

            // if (x)   // Error: "Cannot implicitly convert type 'int' to 'bool'"
            {
                Console.Write("The value of x is nonzero.");
            }

To test a variable of the type int, you have to explicitly compare it to a value, such as zero, as follows:

            if (x != 0)   // The C# way
            {
                Console.Write("The value of x is nonzero.");
            }

In this example, you enter a character from the keyboard and the program checks if the input character is a letter. If it is a letter, it checks if it is lowercase or uppercase. These checks are performed with the IsLetter, and IsLower, both of which return the bool type:

    public class BoolKeyTest
    {
        static void Main()
        {
            Console.Write("Enter a character: ");
            char c = (char)Console.Read();
            if (Char.IsLetter(c))
            {
                if (Char.IsLower(c))
                {
                    Console.WriteLine("The character is lowercase.");
                }
                else
                {
                    Console.WriteLine("The character is uppercase.");
                }
            }
            else
            {
                Console.WriteLine("Not an alphabetic character.");
            }
        }
    }
    /* Sample Output:
        Enter a character: X
        The character is uppercase.
     
        Enter a character: x
        The character is lowercase.

        Enter a character: 2
        The character is not an alphabetic character.
     */





byte


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The byte keyword denotes an integral type that stores values as indicated in the following table.

TypeRangeSize.NET Framework type
byte0 to 255Unsigned 8-bit integerSystem.Byte

You can declare and initialize a byte variable like this example:

byte myByte = 255;  

In the preceding declaration, the integer literal 255 is implicitly converted from int to byte. If the integer literal exceeds the range of byte, a compilation error will occur.

There is a predefined implicit conversion from byte to shortushortintuintlongulongfloatdouble, or decimal.

You cannot implicitly convert non-literal numeric types of larger storage size to byte. For more information on the storage sizes of integral types, see Integral Types Table. Consider, for example, the following two byte variables x and y:

  
byte x = 10, y = 20;  

The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

// Error: conversion from int to byte:  
byte z = x + y;  

To fix this problem, use a cast:

// OK: explicit conversion:  
byte z = (byte)(x + y);  

It is possible though, to use the following statements where the destination variable has the same storage size or a larger storage size:

int x = 10, y = 20;  
int m = x + y;  
long n = x + y;  

Also, there is no implicit conversion from floating-point types to byte. For example, the following statement generates a compiler error unless an explicit cast is used:

// Error: no implicit conversion from double:  
byte x = 3.0;   
// OK: explicit conversion:  
byte y = (byte)3.0;  

When calling overloaded methods, a cast must be used. Consider, for example, the following overloaded methods that use byte and int parameters:

public static void SampleMethod(int i) {}  
public static void SampleMethod(byte b) {}  

Using the byte cast guarantees that the correct type is called, for example:

// Calling the method with the int parameter:  
SampleMethod(5);  
// Calling the method with the byte parameter:  
SampleMethod((byte)5);  

For information on arithmetic expressions with mixed floating-point types and integral types, see float and double.

For more information on implicit numeric conversion rules, see the Implicit Numeric Conversions Table.







char


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The char keyword is used to declare an instance of the System.Char structure that the .NET Framework uses to represent a Unicode character. The value of a Char object is a 16-bit numeric (ordinal) value.

Unicode characters are used to represent most of the written languages throughout the world.

TypeRangeSize.NET Framework type
charU+0000 to U+FFFFUnicode 16-bit characterSystem.Char

Constants of the char type can be written as character literals, hexadecimal escape sequence, or Unicode representation. You can also cast the integral character codes. In the following example four char variables are initialized with the same character X:

            char[] chars = new char[4];

            chars[0] = 'X';        // Character literal
            chars[1] = '\x0058';   // Hexadecimal
            chars[2] = (char)88;   // Cast from integral type
            chars[3] = '\u0058';   // Unicode

            foreach (char c in chars)
            {
                Console.Write(c + " ");
            }
            // Output: X X X X

char can be implicitly converted to ushortintuintlongulongfloatdouble, or decimal. However, there are no implicit conversions from other types to the char type.

The System.Char type provides several static methods for working with char values.







decimal


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations. The approximate range and precision for the decimal type are shown in the following table.

TypeApproximate RangePrecision.NET Framework type
decimal(-7.9 x 1028 to 7.9 x 1028) / (100 to 28)28-29 significant digitsSystem.Decimal

If you want a numeric real literal to be treated as decimal, use the suffix m or M, for example:

  
decimal myMoney = 300.5m;  

Without the suffix m, the number is treated as a double and generates a compiler error.

The integral types are implicitly converted to decimal and the result evaluates to decimal. Therefore you can initialize a decimal variable using an integer literal, without the suffix, as follows:

  
decimal myMoney = 300;  

There is no implicit conversion between floating-point types and the decimal type; therefore, a cast must be used to convert between these two types. For example:

  
      decimal myMoney = 99.9m;  
double x = (double)myMoney;  
myMoney = (decimal)x;  

You can also mix decimal and numeric integral types in the same expression. However, mixing decimal and floating-point types without a cast causes a compilation error.

For more information about implicit numeric conversions, see Implicit Numeric Conversions Table.

For more information about explicit numeric conversions, see Explicit Numeric Conversions Table.

You can format the results by using the String.Format method, or through the Console.Write method, which calls String.Format(). The currency format is specified by using the standard currency format string "C" or "c," as shown in the second example later in this article. For more information about the String.Format method, see String.Format.

The following example causes a compiler error by trying to add double and decimal variables.

double dub = 9;  
// The following line causes an error that reads "Operator '+' cannot be applied to   
// operands of type 'double' and 'decimal'"  
Console.WriteLine(dec + dub);   
  
// You can fix the error by using explicit casting of either operand.  
Console.WriteLine(dec + (decimal)dub);  
Console.WriteLine((double)dec + dub);  
  

The result is the following error:

Operator '+' cannot be applied to operands of type 'double' and 'decimal'

In this example, a decimal and an int are mixed in the same expression. The result evaluates to the decimal type.

    public class TestDecimal
    {
        static void Main()
        {
            decimal d = 9.1m;
            int y = 3;
            Console.WriteLine(d + y);   // Result converted to decimal
        }
    }
    // Output: 12.1

In this example, the output is formatted by using the currency format string. Notice that x is rounded because the decimal places exceed $0.99. The variable y, which represents the maximum exact digits, is displayed exactly in the correct format.

    public class TestDecimalFormat
    {
        static void Main()
        {
            decimal x = 0.999m;
            decimal y = 9999999999999999999999999999m;
            Console.WriteLine("My amount = {0:C}", x);
            Console.WriteLine("Your amount = {0:C}", y);
        }
    }
    /* Output:
        My amount = $1.00
        Your amount = $9,999,999,999,999,999,999,999,999,999.00
    */





double


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The double keyword signifies a simple type that stores 64-bit floating-point values. The following table shows the precision and approximate range for the double type.

TypeApproximate rangePrecision.NET Framework type
double±5.0 × 10−324 to ±1.7 × 1030815-16 digitsSystem.Double

By default, a real numeric literal on the right side of the assignment operator is treated as double. However, if you want an integer number to be treated as double, use the suffix d or D, for example:

  
double x = 3D;  

You can mix numeric integral types and floating-point types in an expression. In this case, the integral types are converted to floating-point types. The evaluation of the expression is performed according to the following rules:

  • If one of the floating-point types is double, the expression evaluates to double, or bool in relational or Boolean expressions.

  • If there is no double type in the expression, it evaluates to float, or bool in relational or Boolean expressions.

A floating-point expression can contain the following sets of values:

  • Positive and negative zero.

  • Positive and negative infinity.

  • Not-a-Number value (NaN).

  • The finite set of nonzero values.

For more information about these values, see IEEE Standard for Binary Floating-Point Arithmetic, available on the IEEE Web site.

In the following example, an int, a short, a float, and a double are added together giving a double result.

    // Mixing types in expressions
    class MixedTypes
    {
        static void Main()
        {
            int x = 3;
            float y = 4.5f;
            short z = 5;
            double w = 1.7E+3;
            // Result of the 2nd argument is a double:
            Console.WriteLine("The sum is {0}", x + y + z + w);
        }
    }
    // Output: The sum is 1712.5





enum


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumeration, Sat is 0Sun is 1Mon is 2, and so forth.

  
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};  

Enumerators can use initializers to override the default values, as shown in the following example.

  
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};  

In this enumeration, the sequence of elements is forced to start from 1 instead of 0. However, including a constant that has the value of 0 is recommended. For more information, see Enumeration Types.

Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example.

  
enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};  

The approved types for an enum are bytesbyteshortushortintuintlong, or ulong.

A variable of type Days can be assigned any value in the range of the underlying type; the values are not limited to the named constants.

The default value of an enum E is the value produced by the expression (E)0.

System_CAPS_ICON_note.jpg Note

An enumerator cannot contain white space in its name.

The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is necessary to convert from enum type to an integral type. For example, the following statement assigns the enumerator Sun to a variable of the type int by using a cast to convert from enum to int.

  
int x = (int)Days.Sun;  

When you apply System.FlagsAttribute to an enumeration that contains elements that can be combined with a bitwise OR operation, the attribute affects the behavior of the enum when it is used with some tools. You can notice these changes when you use tools such as the Console class methods and the Expression Evaluator. (See the third example.)

Just as with any constant, all references to the individual values of an enum are converted to numeric literals at compile time. This can create potential versioning issues as described in Constants.

Assigning additional values to new versions of enums, or changing the values of the enum members in a new version, can cause problems for dependent source code. Enum values often are used in switch statements. If additional elements have been added to the enum type, the default section of the switch statement can be selected unexpectedly.

If other developers use your code, you should provide guidelines about how their code should react if new elements are added to any enum types.

In the following example, an enumeration, Days, is declared. Two enumerators are explicitly converted to integer and assigned to integer variables.

    public class EnumTest
    {
        enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

        static void Main()
        {
            int x = (int)Days.Sun;
            int y = (int)Days.Fri;
            Console.WriteLine("Sun = {0}", x);
            Console.WriteLine("Fri = {0}", y);
        }
    }
    /* Output:
       Sun = 0
       Fri = 5
    */

In the following example, the base-type option is used to declare an enum whose members are of type long. Notice that even though the underlying type of the enumeration is long, the enumeration members still must be explicitly converted to type long by using a cast.

    public class EnumTest2
    {
        enum Range : long { Max = 2147483648L, Min = 255L };
        static void Main()
        {
            long x = (long)Range.Max;
            long y = (long)Range.Min;
            Console.WriteLine("Max = {0}", x);
            Console.WriteLine("Min = {0}", y);
        }
    }
    /* Output:
       Max = 2147483648
       Min = 255
    */

The following code example illustrates the use and effect of the System.FlagsAttribute attribute on an enum declaration.

    // Add the attribute Flags or FlagsAttribute.
    [Flags]
    public enum CarOptions
    {
        // The flag for SunRoof is 0001.
        SunRoof = 0x01,
        // The flag for Spoiler is 0010.
        Spoiler = 0x02,
        // The flag for FogLights is 0100.
        FogLights = 0x04,
        // The flag for TintedWindows is 1000.
        TintedWindows = 0x08,
    }

    class FlagTest
    {
        static void Main()
        {
            // The bitwise OR of 0001 and 0100 is 0101.
            CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;

            // Because the Flags attribute is specified, Console.WriteLine displays
            // the name of each enum element that corresponds to a flag that has
            // the value 1 in variable options.
            Console.WriteLine(options);
            // The integer value of 0101 is 5.
            Console.WriteLine((int)options);
        }
    }
    /* Output:
       SunRoof, FogLights
       5
    */

If you remove Flags, the example displays the following values:

5

5




float


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The float keyword signifies a simple type that stores 32-bit floating-point values. The following table shows the precision and approximate range for the float type.

TypeApproximate rangePrecision.NET Framework type
float-3.4 × 1038to +3.4 × 10387 digitsSystem.Single

By default, a real numeric literal on the right side of the assignment operator is treated as double. Therefore, to initialize a float variable, use the suffix f or F, as in the following example:

  
float x = 3.5F;  

If you do not use the suffix in the previous declaration, you will get a compilation error because you are trying to store a double value into a float variable.

You can mix numeric integral types and floating-point types in an expression. In this case, the integral types are converted to floating-point types. The evaluation of the expression is performed according to the following rules:

  • If one of the floating-point types is double, the expression evaluates to double or bool in relational or Boolean expressions.

  • If there is no double type in the expression, the expression evaluates to float or bool in relational or Boolean expressions.

A floating-point expression can contain the following sets of values:

  • Positive and negative zero

  • Positive and negative infinity

  • Not-a-Number value (NaN)

  • The finite set of nonzero values

For more information about these values, see IEEE Standard for Binary Floating-Point Arithmetic, available on the IEEE Web site.

In the following example, an int, a short, and a float are included in a mathematical expression giving a float result. (Remember that float is an alias for the System.Single type.) Notice that there is no double in the expression.

    class FloatTest 
    {
        static void Main() 
        {
            int x = 3;
            float y = 4.5f;
            short z = 5;
            var result = x * y / z;
            Console.WriteLine("The result is {0}", result);
            Type type = result.GetType();
            Console.WriteLine("result is of type {0}", type.ToString());
        }
    }
    /* Output: 
      The result is 2.7
      result is of type System.Single //'float' is alias for 'Single'
     */




int


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The int keyword denotes an integral type that stores values according to the size and range shown in the following table.

TypeRangeSize.NET Framework typeDefault Value
int-2,147,483,648 to 2,147,483,647Signed 32-bit integerSystem.Int320

You can declare and initialize a variable of the type int like this example:

  
int i = 123;  

When an integer literal has no suffix, its type is the first of these types in which its value can be represented: intuintlongulong. In this example, it is of the type int.

There is a predefined implicit conversion from int to longfloatdouble, or decimal. For example:

// '123' is an int, so an implicit conversion takes place here:  
float f = 123;  

There is a predefined implicit conversion from sbytebyteshortushort, or char to int. For example, the following assignment statement will produce a compilation error without a cast:

long aLong = 22;  
int i1 = aLong;       // Error: no implicit conversion from long.  
int i2 = (int)aLong;  // OK: explicit conversion.  

Notice also that there is no implicit conversion from floating-point types to int. For example, the following statement generates a compiler error unless an explicit cast is used:

  
      int x = 3.0;         // Error: no implicit conversion from double.  
int y = (int)3.0;    // OK: explicit conversion.  

For more information on arithmetic expressions with mixed floating-point types and integral types, see float and double.




long


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The long keyword denotes an integral type that stores values according to the size and range shown in the following table.

TypeRangeSize.NET Framework type
long–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807Signed 64-bit integerSystem.Int64

You can declare and initialize a long variable like this example:

  
long long1 = 4294967296;  

When an integer literal has no suffix, its type is the first of these types in which its value can be represented: intuintlongulong. In the preceding example, it is of the type long because it exceeds the range of uint (see Integral Types Table for the storage sizes of integral types).

You can also use the suffix L with the long type like this:

  
long long2 = 4294967296L;  

When you use the suffix L, the type of the literal integer is determined to be either long or ulong according to its size. In the case it is long because it less than the range of ulong.

A common use of the suffix is with calling overloaded methods. Consider, for example, the following overloaded methods that use long and int parameters:

public static void SampleMethod(int i) {}  
public static void SampleMethod(long l) {}  

Using the suffix L guarantees that the correct type is called, for example:

SampleMethod(5);    // Calling the method with the int parameter  
SampleMethod(5L);   // Calling the method with the long parameter  

You can use the long type with other numeric integral types in the same expression, in which case the expression is evaluated as long (or bool in the case of relational or Boolean expressions). For example, the following expression evaluates as long:

898L + 88  

System_CAPS_ICON_note.jpg Note

You can also use the lowercase letter "l" as a suffix. However, this generates a compiler warning because the letter "l" is easily confused with the digit "1." Use "L" for clarity.

For information on arithmetic expressions with mixed floating-point types and integral types, see float and double.

There is a predefined implicit conversion from long to floatdouble, or decimal. Otherwise a cast must be used. For example, the following statement will produce a compilation error without an explicit cast:

int x = L;        // Error: no implicit conversion from long to int  
int x = (int)L;   // OK: explicit conversion to int  

There is a predefined implicit conversion from sbytebyteshortushortintuint, or char to long.

Notice also that there is no implicit conversion from floating-point types to long. For example, the following statement generates a compiler error unless an explicit cast is used:

  
      long x = 3.0;         // Error: no implicit conversion from double  
long y = (long)3.0;   // OK: explicit conversion  




sbyte


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The sbyte keyword indicates an integral type that stores values according to the size and range shown in the following table.

TypeRangeSize.NET Framework type
sbyte-128 to 127Signed 8-bit integerSystem.SByte

You can declare and initialize an sbyte variable in this manner:

  
sbyte sByte1 = 127;  

In the previous declaration, the integer literal 127 is implicitly converted from int to sbyte. If the integer literal exceeds the range of sbyte, a compilation error will occur.

A cast must be used when calling overloaded methods. Consider, for example, the following overloaded methods that use sbyteand int parameters:

public static void SampleMethod(int i) {}  
public static void SampleMethod(sbyte b) {}  

Using the sbyte cast guarantees that the correct type is called, for example:

// Calling the method with the int parameter:  
SampleMethod(5);  
// Calling the method with the sbyte parameter:  
SampleMethod((sbyte)5);  

There is a predefined implicit conversion from sbyte to shortintlongfloatdouble, or decimal.

You cannot implicitly convert nonliteral numeric types of larger storage size to sbyte (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two sbyte variables x and y:

  
sbyte x = 10, y = 20;  

The following assignment statement will produce a compilation error, because the arithmetic expression on the right side of the assignment operator evaluates to int by default.

  
sbyte z = x + y;   // Error: conversion from int to sbyte  

To fix this problem, cast the expression as in the following example:

  
sbyte z = (sbyte)(x + y);   // OK: explicit conversion  

It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:

  
      sbyte x = 10, y = 20;  
int m = x + y;  
long n = x + y;  

Notice also that there is no implicit conversion from floating-point types to sbyte. For example, the following statement generates a compiler error unless an explicit cast is used:

  
      sbyte x = 3.0;         // Error: no implicit conversion from double  
sbyte y = (sbyte)3.0;  // OK: explicit conversion  

For information about arithmetic expressions with mixed floating-point types and integral types, see float and double.

For more information about implicit numeric conversion rules, see the Implicit Numeric Conversions Table.




short


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The short keyword denotes an integral data type that stores values according to the size and range shown in the following table.

TypeRangeSize.NET Framework type
short-32,768 to 32,767Signed 16-bit integerSystem.Int16

You can declare and initialize a short variable like this example:

  
short x = 32767;  

In the preceding declaration, the integer literal 32767 is implicitly converted from int to short. If the integer literal does not fit into a short storage location, a compilation error will occur.

A cast must be used when calling overloaded methods. Consider, for example, the following overloaded methods that use shortand int parameters:

public static void SampleMethod(int i) {}  
public static void SampleMethod(short s) {}  

Using the short cast guarantees that the correct type is called, for example:

SampleMethod(5);         // Calling the method with the int parameter  
SampleMethod((short)5);  // Calling the method with the short parameter  

There is a predefined implicit conversion from short to intlongfloatdouble, or decimal.

You cannot implicitly convert nonliteral numeric types of larger storage size to short (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two short variables x and y:

  
short x = 5, y = 12;  

The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

short   z = x + y; // Error: no conversion from int to short

To fix this problem, use a cast:

short   z = (  short  )(x + y); // OK: explicit conversion

It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:

int m = x + y;  
long n = x + y;  

There is no implicit conversion from floating-point types to short. For example, the following statement generates a compiler error unless an explicit cast is used:

  
      short x = 3.0;          // Error: no implicit conversion from double  
short y = (short)3.0;   // OK: explicit conversion  

For information on arithmetic expressions with mixed floating-point types and integral types, see float and double.

For more information on implicit numeric conversion rules, see the Implicit Numeric Conversions Table.




struct


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:

public struct Book  
{  
    public decimal price;  
    public string title;  
    public string author;  
}  

Structs can also contain constructorsconstantsfieldsmethodspropertiesindexersoperatorsevents, and nested types, although if several such members are required, you should consider making your type a class instead.

For examples, see Using Structs.

Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.

For more information, see Structs.

For examples and more information, see Using Structs.




uint


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The uint keyword signifies an integral type that stores values according to the size and range shown in the following table.

TypeRangeSize.NET Framework type
uint0 to 4,294,967,295Unsigned 32-bit integerSystem.UInt32

Note The uint type is not CLS-compliant. Use int whenever possible.

You can declare and initialize a variable of the type uint like this example:

  
uint myUint = 4294967290;  

When an integer literal has no suffix, its type is the first of these types in which its value can be represented: intuintlongulong. In this example, it is uint:

  
uint uInt1 = 123;  

You can also use the suffix u or U, such as this:

  
uint uInt2 = 123U;  

When you use the suffix U or u, the type of the literal is determined to be either uint or ulong according to the numeric value of the literal. For example:

Console.WriteLine(44U.GetType());  
Console.WriteLine(323442434344U.GetType());  

This code displays System.UInt32, followed by System.UInt64 -- the underlying types for uint and ulong respectively -- because the second literal is too large to be stored by the uint type.

There is a predefined implicit conversion from uint to longulongfloatdouble, or decimal. For example:

float myFloat = 4294967290;   // OK: implicit conversion to float  

There is a predefined implicit conversion from byteushort, or char to uint. Otherwise you must use a cast. For example, the following assignment statement will produce a compilation error without a cast:

long aLong = 22;  
// Error -- no implicit conversion from long:  
uint uInt1 = aLong;   
// OK -- explicit conversion:  
uint uInt2 = (uint)aLong;  

Notice also that there is no implicit conversion from floating-point types to uint. For example, the following statement generates a compiler error unless an explicit cast is used:

// Error -- no implicit conversion from double:  
uint x = 3.0;  
// OK -- explicit conversion:  
uint y = (uint)3.0;   

For information about arithmetic expressions with mixed floating-point types and integral types, see float and double.

For more information about implicit numeric conversion rules, see the Implicit Numeric Conversions Table.




ulong


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The ulong keyword denotes an integral type that stores values according to the size and range shown in the following table.

TypeRangeSize.NET Framework type
ulong0 to 18,446,744,073,709,551,615Unsigned 64-bit integerSystem.UInt64

You can declare and initialize a ulong variable like this example:

  
ulong uLong = 9223372036854775808;  

When an integer literal has no suffix, its type is the first of these types in which its value can be represented: intuintlongulong. In the example above, it is of the type ulong.

You can also use suffixes to specify the type of the literal according to the following rules:

  • If you use L or l, the type of the literal integer will be either long or ulong according to its size.

    System_CAPS_ICON_note.jpg Note

    You can use the lowercase letter "l" as a suffix. However, this generates a compiler warning because the letter "l" is easily confused with the digit "1." Use "L" for clarity.

  • If you use U or u, the type of the literal integer will be either uint or ulong according to its size.

  • If you use UL, ul, Ul, uL, LU, lu, Lu, or lU, the type of the literal integer will be ulong.

    For example, the output of the following three statements will be the system type UInt64, which corresponds to the alias ulong:

    Console.WriteLine(9223372036854775808L.GetType());  
    Console.WriteLine(123UL.GetType());  
    Console.WriteLine((123UL + 456).GetType());  
    
    

A common use of the suffix is with calling overloaded methods. Consider, for example, the following overloaded methods that use ulong and int parameters:

public static void SampleMethod(int i) {}  
public static void SampleMethod(ulong l) {}  

Using a suffix with the ulong parameter guarantees that the correct type is called, for example:

SampleMethod(5);    // Calling the method with the int parameter  
SampleMethod(5UL);  // Calling the method with the ulong parameter  

There is a predefined implicit conversion from ulong to floatdouble, or decimal.

There is no implicit conversion from ulong to any integral type. For example, the following statement will produce a compilation error without an explicit cast:

long long1 = UL;   // Error: no implicit conversion from ulong  

There is a predefined implicit conversion from byteushortuint, or char to ulong.

Also, there is no implicit conversion from floating-point types to ulong. For example, the following statement generates a compiler error unless an explicit cast is used:

// Error -- no implicit conversion from double:  
ulong x = 3.0;  
// OK -- explicit conversion:  
ulong y = (ulong)3.0;    

For information on arithmetic expressions with mixed floating-point types and integral types, see float and double.

For more information on implicit numeric conversion rules, see the Implicit Numeric Conversions Table.






ushort


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The ushort keyword indicates an integral data type that stores values according to the size and range shown in the following table.

TypeRangeSize.NET Framework type
ushort0 to 65,535Unsigned 16-bit integerSystem.UInt16

You can declare and initialize a ushort variable such as this example:

  
ushort myShort = 65535;  

In the previous declaration, the integer literal 65535 is implicitly converted from int to ushort. If the integer literal exceeds the range of ushort, a compilation error will occur.

A cast must be used when you call overloaded methods. Consider, for example, the following overloaded methods that use ushort and int parameters:

public static void SampleMethod(int i) {}  
public static void SampleMethod(ushort s) {}  

Using the ushort cast guarantees that the correct type is called, for example:

// Calls the method with the int parameter:  
SampleMethod(5);  
// Calls the method with the ushort parameter:  
SampleMethod((ushort)5);    

There is a predefined implicit conversion from ushort to intuintlongulongfloatdouble, or decimal.

There is a predefined implicit conversion from byte or char to ushort. Otherwise a cast must be used to perform an explicit conversion. Consider, for example, the following two ushort variables x and y:

  
ushort x = 5, y = 12;  

The following assignment statement will produce a compilation error, because the arithmetic expression on the right side of the assignment operator evaluates to int by default.

  
ushort z = x + y;   // Error: conversion from int to ushort  

To fix this problem, use a cast:

  
ushort z = (ushort)(x + y);   // OK: explicit conversion   

It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:

int m = x + y;  
long n = x + y;  

Notice also that there is no implicit conversion from floating-point types to ushort. For example, the following statement generates a compiler error unless an explicit cast is used:

// Error -- no implicit conversion from double:  
ushort x = 3.0;   
// OK -- explicit conversion:  
ushort y = (ushort)3.0;  

For information about arithmetic expressions with mixed floating-point types and integral types, see float and double.

For more information about implicit numeric conversion rules, see the Implicit Numeric Conversions Table.







Reference Types


https://msdn.microsoft.com/en-us/library/490f96s2.aspx




class


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Classes are declared using the keyword class, as shown in the following example:

  
      class TestClass  
{  
    // Methods, properties, fields, events, delegates   
    // and nested classes go here.  
}  

Only single inheritance is allowed in C#. In other words, a class can inherit implementation from one base class only. However, a class can implement more than one interface. The following table shows examples of class inheritance and interface implementation:

InheritanceExample
Noneclass ClassA { }
Singleclass DerivedClass: BaseClass { }
None, implements two interfacesclass ImplClass: IFace1, IFace2 { }
Single, implements one interfaceclass ImplDerivedClass: BaseClass, IFace1 { }

Classes that you declare directly within a namespace, not nested within other classes, can be either public or internal. Classes are internal by default.

Class members, including nested classes, can be publicprotected internalprotectedinternal, or private. Members are private by default.

For more information, see Access Modifiers.

You can declare generic classes that have type parameters. For more information, see Generic Classes.

A class can contain declarations of the following members:

The following example demonstrates declaring class fields, constructors, and methods. It also demonstrates object instantiation and printing instance data. In this example, two classes are declared, the Child class, which contains two private fields (name and age) and two public methods. The second class, StringTest, is used to contain Main.

    class Child
    {
        private int age;
        private string name;

        // Default constructor:
        public Child()
        {
            name = "N/A";
        }

        // Constructor:
        public Child(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        // Printing method:
        public void PrintChild()
        {
            Console.WriteLine("{0}, {1} years old.", name, age);
        }
    }

    class StringTest
    {
        static void Main()
        {
            // Create objects by using the new operator:
            Child child1 = new Child("Craig", 11);
            Child child2 = new Child("Sally", 10);

            // Create an object using the default constructor:
            Child child3 = new Child();

            // Display results:
            Console.Write("Child #1: ");
            child1.PrintChild();
            Console.Write("Child #2: ");
            child2.PrintChild();
            Console.Write("Child #3: ");
            child3.PrintChild();
        }
    }
    /* Output:
        Child #1: Craig, 11 years old.
        Child #2: Sally, 10 years old.
        Child #3: N/A, 0 years old.
    */

Notice, in the preceding example, that the private fields (name and age) can only be accessed through the public methods of the Child class. For example, you cannot print the child's name, from the Main method, using a statement like this:

Console.Write(child1.name);   // Error  

Accessing private members of Child from Main would only be possible if Main were a member of the class.

Types declared inside a class without an access modifier default to private, so the data members in this example would still be private if the keyword were removed.

Finally, notice that for the object created using the default constructor (child3), the age field was initialized to zero by default.






delegate


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The declaration of a delegate type is similar to a method signature. It has a return value and any number of parameters of any type:

public delegate void TestDelegate(string message);  
public delegate int TestDelegate(MyType m, long num);  

delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. For applications of delegates, see Delegates and Generic Delegates.

Delegates are the basis for Events.

A delegate can be instantiated by associating it either with a named or anonymous method. For more information, see Named Methods and Anonymous Methods.

The delegate must be instantiated with a method or lambda expression that has a compatible return type and input parameters. For more information on the degree of variance that is allowed in the method signature, see Variance in Delegates. For use with anonymous methods, the delegate and the code to be associated with it are declared together. Both ways of instantiating delegates are discussed in this section.

    // Declare delegate -- defines required signature:
    delegate double MathAction(double num);

    class DelegateTest
    {
        // Regular method that matches signature:
        static double Double(double input)
        {
            return input * 2;
        }

        static void Main()
        {
            // Instantiate delegate with named method:
            MathAction ma = Double;

            // Invoke delegate ma:
            double multByTwo = ma(4.5);
            Console.WriteLine("multByTwo: {0}", multByTwo);

            // Instantiate delegate with anonymous method:
            MathAction ma2 = delegate(double input)
            {
                return input * input;
            };

            double square = ma2(5);
            Console.WriteLine("square: {0}", square);

            // Instantiate delegate with lambda expression
            MathAction ma3 = s => s * s * s;
            double cube = ma3(4.375);

            Console.WriteLine("cube: {0}", cube);
        }
        // Output:
        // multByTwo: 9
        // square: 25
        // cube: 83.740234375
    }




dynamic


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).

Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.

The following example contrasts a variable of type dynamic to a variable of type object. To verify the type of each variable at compile time, place the mouse pointer over dyn or obj in the WriteLine statements. IntelliSense shows dynamic for dyn and object for obj.

    class Program
    {
        static void Main(string[] args)
        {
            dynamic dyn = 1;
            object obj = 1;

            // Rest the mouse pointer over dyn and obj to see their
            // types at compile time.
            System.Console.WriteLine(dyn.GetType());
            System.Console.WriteLine(obj.GetType());
        }
    }

The WriteLine statements display the run-time types of dyn and obj. At that point, both have the same type, integer. The following output is produced:

System.Int32

System.Int32

To see the difference between dyn and obj at compile time, add the following two lines between the declarations and the WriteLine statements in the previous example.

dyn = dyn + 3;  
obj = obj + 3;  

A compiler error is reported for the attempted addition of an integer and an object in expression obj + 3. However, no error is reported for dyn + 3. The expression that contains dyn is not checked at compile time because the type of dyn is dynamic.

The dynamic keyword can appear directly or as a component of a constructed type in the following situations:

  • In declarations, as the type of a property, field, indexer, parameter, return value, local variable, or type constraint. The following class definition uses dynamic in several different declarations.

        class ExampleClass
        {
            // A dynamic field.
            static dynamic field;
    
            // A dynamic property.
            dynamic prop { get; set; }
    
            // A dynamic return type and a dynamic parameter type.
            public dynamic exampleMethod(dynamic d)
            {
                // A dynamic local variable.
                dynamic local = "Local variable";
                int two = 2;
    
                if (d is int)
                {
                    return local;
                }
                else
                {
                    return two;
                }
            }
        }
    

  • In explicit type conversions, as the target type of a conversion.

            static void convertToDynamic()
            {
                dynamic d;
                int i = 20;
                d = (dynamic)i;
                Console.WriteLine(d);
    
                string s = "Example string.";
                d = (dynamic)s;
                Console.WriteLine(d);
    
                DateTime dt = DateTime.Today;
                d = (dynamic)dt;
                Console.WriteLine(d);
    
            }
            // Results:
            // 20
            // Example string.
            // 2/17/2009 9:12:00 AM
    

  • In any context where types serve as values, such as on the right side of an is operator or an as operator, or as the argument to typeof as part of a constructed type. For example, dynamic can be used in the following expressions.

                int i = 8;
                dynamic d;
                // With the is operator.
                // The dynamic type behaves like object. The following
                // expression returns true unless someVar has the value null.
                if (someVar is dynamic) { }
    
                // With the as operator.
                d = i as dynamic;
    
                // With typeof, as part of a constructed type.
                Console.WriteLine(typeof(List<dynamic>));
    
                // The following statement causes a compiler error.
                //Console.WriteLine(typeof(dynamic));
    

The following example uses dynamic in several declarations. The Main method also contrasts compile-time type checking with run-time type checking.

using System;

namespace DynamicExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass ec = new ExampleClass();
            Console.WriteLine(ec.exampleMethod(10));
            Console.WriteLine(ec.exampleMethod("value"));

            // The following line causes a compiler error because exampleMethod
            // takes only one argument.
            //Console.WriteLine(ec.exampleMethod(10, 4));

            dynamic dynamic_ec = new ExampleClass();
            Console.WriteLine(dynamic_ec.exampleMethod(10));

            // Because dynamic_ec is dynamic, the following call to exampleMethod
            // with two arguments does not produce an error at compile time.
            // However, itdoes cause a run-time error. 
            //Console.WriteLine(dynamic_ec.exampleMethod(10, 4));
        }
    }

    class ExampleClass
    {
        static dynamic field;
        dynamic prop { get; set; }

        public dynamic exampleMethod(dynamic d)
        {
            dynamic local = "Local variable";
            int two = 2;

            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
}
// Results:
// Local variable
// 2
// Local variable



interface


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

An interface contains only the signatures of methodspropertiesevents or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition. In the following example, class ImplementationClass must implement a method named SampleMethod that has no parameters and returns void.

For more information and examples, see Interfaces.

    interface ISampleInterface
    {
        void SampleMethod();
    }

    class ImplementationClass : ISampleInterface
    {
        // Explicit interface member implementation: 
        void ISampleInterface.SampleMethod()
        {
            // Method implementation.
        }

        static void Main()
        {
            // Declare an interface instance.
            ISampleInterface obj = new ImplementationClass();

            // Call the member.
            obj.SampleMethod();
        }
    }

An interface can be a member of a namespace or a class and can contain signatures of the following members:

An interface can inherit from one or more base interfaces.

When a base type list contains a base class and interfaces, the base class must come first in the list.

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

For more details and code examples on explicit interface implementation, see Explicit Interface Implementation.

The following example demonstrates interface implementation. In this example, the interface contains the property declaration and the class contains the implementation. Any instance of a class that implements IPoint has integer properties x and y.

    interface IPoint
    {
       // Property signatures:
       int x
       {
          get;
          set;
       }

       int y
       {
          get;
          set;
       }
    }

    class Point : IPoint
    {
       // Fields:
       private int _x;
       private int _y;

       // Constructor:
       public Point(int x, int y)
       {
          _x = x;
          _y = y;
       }

       // Property implementation:
       public int x
       {
          get
          {
             return _x;
          }

          set
          {
             _x = value;
          }
       }

       public int y
       {
          get
          {
             return _y;
          }
          set
          {
             _y = value;
          }
       }
    }

    class MainClass
    {
       static void PrintPoint(IPoint p)
       {
          Console.WriteLine("x={0}, y={1}", p.x, p.y);
       }

       static void Main()
       {
          Point p = new Point(2, 3);
          Console.Write("My Point: ");
          PrintPoint(p);
       }
    }
    // Output: My Point: x=2, y=3






object


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The object type is an alias for Object in the .NET Framework. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object. When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed. For more information, see Boxing and Unboxing.

The following sample shows how variables of type object can accept values of any data type and how variables of type objectcan use methods on Object from the .NET Framework.

class ObjectTest
{
   public int i = 10;
}

class MainClass2
{
   static void Main()
   {
      object a;
      a = 1;   // an example of boxing
      Console.WriteLine(a);
      Console.WriteLine(a.GetType());
      Console.WriteLine(a.ToString());

      a = new ObjectTest();
      ObjectTest classRef;
      classRef = (ObjectTest)a;
      Console.WriteLine(classRef.i);
   }
}
/* Output
    1
    System.Int32
    1
 * 10
*/





string


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

  
      string a = "hello";  
string b = "h";  
// Append to contents of 'b'  
b += "ello";  
Console.WriteLine(a == b);  
Console.WriteLine((object)a == (object)b);  

This displays "True" and then "False" because the content of the strings are equivalent, but a and b do not refer to the same string instance.

The + operator concatenates strings:

  
string a = "good " + "morning";  

This creates a string object that contains "good morning".

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

  
      string b = "h";  
b += "ello";  

The [] operator can be used for readonly access to individual characters of a string:

  
      string str = "test";  
char x = str[2];  // x = 's';  

String literals are of type string and can be written in two forms, quoted and @-quoted. Quoted string literals are enclosed in double quotation marks ("):

"good morning"  // a string literal  

String literals can contain any character literal. Escape sequences are included. The following example uses escape sequence \\for backslash, \u0066 for the letter f, and \n for newline.

  
      string a = "\\\u0066\n";  
Console.WriteLine(a);  

System_CAPS_ICON_note.jpg Note

The escape code \udddd (where dddd is a four-digit number) represents the Unicode character U+dddd. Eight-digit Unicode escape codes are also recognized: \Udddddddd.

Verbatim string literals start with @ and are also enclosed in double quotation marks. For example:

@"good morning"  // a string literal  

The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:

@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"  

To include a double quotation mark in an @-quoted string, double it:

@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.  

Another use of the @ symbol is to use referenced (/reference) identifiers that are C# keywords.

For more information about strings in C#, see Strings.

    class SimpleStringTest 
    {
       static void Main()
       {
          string a = "\u0068ello ";
          string b = "world";
          Console.WriteLine( a + b );
          Console.WriteLine( a + b == "Hello World" ); // == performs a case-sensitive comparison
       }
    }
    /* Output:
        hello world
        False
     */





Interpolated Strings


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Used to construct strings. An interpolated string expression looks like a template string that contains expressions. An interpolated string expression creates a string by replacing the contained expressions with the ToString represenations of the expressions’ results. An interpolated string is easier to understand with respect to arguments than Composite Formatting. Here is an example of an interpolated string:

Console.WriteLine($"Name = {name}, hours = {hours:hh}")  

The structure of an interpolated string is as follows:

$ " <text> { <interpolation-expression> <optional-comma-field-width> <optional-colon-format> } <text> ... } "  

You can use an interpolated string anywhere you can use a string literal. When running your program would execute the code with the interpolated string literal, the code computes a new string literal by evaluating the interpolation expressions. This computation occurs each time the code with the interpolated string executes.

To include a curly brace ("{" or "}") in an interpolated string use two curly braces, "{{" or "}}". See the Implicit Conversions section for more details.

There are implicit type conversions from an interpolated string:

var s = $"hello, {name}"  
System.IFormattable s = $"Hello, {name}"  
System.FormattableString s = $"Hello, {name}"  
  

The first example produces a string value where all the string interpolation values have been computed. It is the final result and has type string. All occurrences of double curly braces (“{{“ and “}}”) are converted to a single curly brace.

The second example produces an IFormattable variable that allows you to convert the string with invariant context. This is useful for getting numeric and data formats correct in different languages. All occurrences of double curly braces (“{{“ and “}}”) remain as double curly braces, until you format the string with ToString. All contained interpolation expressions are converted to {0}, {1}, and so on.

s.ToString(null, System.Globalization.CultureInfo.InvariantCulture);  

The third example produces a FormattableString, which allows you to inspect the objects that result from the interpolation computations. Inspecting objects and how they render as strings might, for example, help you protect against an injection attack if you were building a query. With FormattableString, you have convenience operations to produce the InvariantCulture and CurrentCulture string results. All occurrences of double curly braces (“{{“ and “}}”) remain as double curly braces, until you format. All contained interpolation expressions are converted to {0}, {1}, and so on.

$"Name = {name}, hours = {hours:hh}"  
var s = $"hello, {name}"  
System.IFormattable s = $"Hello, {name}"  
System.FormattableString s = $"Hello, {name}"  
$"{person.Name, 20} is {person.Age:D3} year {(p.Age == 1 ? "" : "s")} old."  
  

You do not need to quote the quotation characters within the contained interpolation expressions because interpolated string expressions start with $, and the compiler scans the contained interpolation expressions as balanced text until it finds a comma, colon, or close curly brace. For the same reasons, the last example uses parentheses to allow the conditional expression (p.Age == 1 ? "" : "s") to be inside the interpolation expression without the colon starting a format specification. Outside of the contained interpolation expression (but still within the interpolated string expression) you escape quotation characters as you normally would.

expression:  
    interpolated-string-expression  
  
interpolated-string-expression:  
    interpolated-string-start interpolations interpolated-string-end  
  
interpolations:  
    single-interpolation  
    single-interpolation interpolated-string-mid interpolations  
  
single-interpolation:  
    interpolation-start  
    interpolation-start : regular-string-literal  
  
interpolation-start:  
    expression  
    expression , expression  





void


https://msdn.microsoft.com/en-us/library/yah0tteb.aspx


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

When used as the return type for a method, void specifies that the method doesn't return a value.

void isn't allowed in the parameter list of a method. A method that takes no parameters and returns no value is declared as follows:

public void SampleMethod()  
{  
    // Body of the method.  
}  
  

void is also used in an unsafe context to declare a pointer to an unknown type. For more information, see Pointer types.

void is an alias for the .NET Framework System.Void type.






var


https://msdn.microsoft.com/en-us/library/bb383973.aspx


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed  
int i = 10; //explicitly typed  

For more information, see Implicitly Typed Local Variables and Type Relationships in LINQ Query Operations.

The following example shows two query expressions. In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable<string>. However, in the second expression, varmust be used because the result is a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

            // Example #1: var is optional because
            // the select clause specifies a string
            string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
            var wordQuery = from word in words
                            where word[0] == 'g'
                            select word;

            // Because each element in the sequence is a string, 
            // not an anonymous type, var is optional here also.
            foreach (string s in wordQuery)
            {
                Console.WriteLine(s);
            }

            // Example #2: var is required because
            // the select clause specifies an anonymous type
            var custQuery = from cust in customers
                            where cust.City == "Phoenix"
                            select new { cust.Name, cust.Phone };

            // var must be used because each item 
            // in the sequence is an anonymous type
            foreach (var item in custQuery)
            {
                Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
            }





Reference Tables for Types


https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx





Built-In Types Table


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The following table shows the keywords for built-in C# types, which are aliases of predefined types in the System namespace.

C# Type.NET Framework Type
boolSystem.Boolean
byteSystem.Byte
sbyteSystem.SByte
charSystem.Char
decimalSystem.Decimal
doubleSystem.Double
floatSystem.Single
intSystem.Int32
uintSystem.UInt32
longSystem.Int64
ulongSystem.UInt64
objectSystem.Object
shortSystem.Int16
ushortSystem.UInt16
stringSystem.String

All of the types in the table, except object and string, are referred to as simple types.

The C# type keywords and their aliases are interchangeable. For example, you can declare an integer variable by using either of the following declarations:

int x = 123;  
System.Int32 x = 123;  

To display the actual type for any C# type, use the system method GetType(). For example, the following statement displays the system alias that represents the type of myVariable:

Console.WriteLine(myVariable.GetType());  

You can also use the typeof operator.




Integral Types Table


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The following table shows the sizes and ranges of the integral types, which constitute a subset of simple types.

TypeRangeSize
sbyte-128 to 127Signed 8-bit integer
byte0 to 255Unsigned 8-bit integer
charU+0000 to U+ffffUnicode 16-bit character
short-32,768 to 32,767Signed 16-bit integer
ushort0 to 65,535Unsigned 16-bit integer
int-2,147,483,648 to 2,147,483,647Signed 32-bit integer
uint0 to 4,294,967,295Unsigned 32-bit integer
long-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807Signed 64-bit integer
ulong0 to 18,446,744,073,709,551,615Unsigned 64-bit integer

If the value represented by an integer literal exceeds the range of ulong, a compilation error will occur.




Floating-Point Types Table


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The following table shows the precision and approximate ranges for the floating-point types.

TypeApproximate rangePrecision
float±1.5e−45 to ±3.4e387 digits
double±5.0e−324 to ±1.7e30815-16 digits




Default Values Table


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The following table shows the default values of value types returned by the default constructors. Default constructors are invoked by using the new operator, as follows:

int myInt = new int();  

The preceding statement has the same effect as the following statement:

int myInt = 0;  

Remember that using uninitialized variables in C# is not allowed.

Value typeDefault value
boolfalse
byte0
char'\0'
decimal0.0M
double0.0D
enumThe value produced by the expression (E)0, where E is the enum identifier.
float0.0F
int0
long0L
sbyte0
short0
structThe value produced by setting all value-type fields to their default values and all reference-type fields to null.
uint0
ulong0
ushort0




Value Types Table


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The following table lists the C# value types by category.

Value typeCategoryType Suffix
boolBoolean
byteUnsigned, numeric, integral
charUnsigned, numeric, integral
decimalNumeric, decimalM or m
doubleNumeric, floating-pointD or d
enumEnumeration
floatNumeric, floating-pointF or f
intSigned, numeric, integral
longSigned, numeric, integralL or l
sbyteSigned, numeric, integral
shortSigned, numeric, integral
structUser-defined structure
uintUnsigned, numeric, integralU or u
ulongUnsigned, numeric, integralUL or ul
ushortUnsigned, numeric, integral




Implicit Numeric Conversions Table


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The following table shows the predefined implicit numeric conversions. Implicit conversions might occur in many situations, including method invoking and assignment statements.

FromTo
sbyteshortintlongfloatdouble, or decimal
byteshortushortintuintlongulongfloatdouble, or decimal
shortintlongfloatdouble, or decimal
ushortintuintlongulongfloatdouble, or decimal
intlongfloatdouble, or decimal
uintlongulongfloatdouble, or decimal
longfloatdouble, or decimal
charushortintuintlongulongfloatdouble, or decimal
floatdouble
ulongfloatdouble, or decimal
  • Precision but not magnitude might be lost in the conversions from intuintlong, or ulong to float and from long or ulong to double.

  • There are no implicit conversions to the char type.

  • There are no implicit conversions between floating-point types and the decimal type.

  • A constant expression of type int can be converted to sbytebyteshortushortuint, or ulong, provided the value of the constant expression is within the range of the destination type.





Explicit Numeric Conversions Table


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Explicit numeric conversion is used to convert any numeric type to any other numeric type, for which there is no implicit conversion, by using a cast expression. The following table shows these conversions.

For more information about conversions, see Casting and Type Conversions.

FromTo
sbytebyteushortuintulong, or char
byteSbyte or char
shortsbytebyteushortuintulong, or char
ushortsbytebyteshort, or char
intsbytebyteshortushortuintulong,or char
uintsbytebyteshortushortint, or char
longsbytebyteshortushortintuintulong, or char
ulongsbytebyteshortushortintuintlong, or char
charsbytebyte, or short
floatsbytebyteshortushortintuintlongulongchar,or decimal
doublesbytebyteshortushortintuintlongulongcharfloat,or decimal
decimalsbytebyteshortushortintuintlongulongcharfloat, or double
  • The explicit numeric conversion may cause loss of precision or result in throwing exceptions.

  • When you convert a decimal value to an integral type, this value is rounded towards zero to the nearest integral value. If the resulting integral value is outside the range of the destination type, an OverflowException is thrown.

  • When you convert from a double or float value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.

  • When you convert double to float, the double value is rounded to the nearest float value. If the double value is too small or too large to fit into the destination type, the result will be zero or infinity.

  • When you convert float or double to decimal, the source value is converted to decimal representation and rounded to the nearest number after the 28th decimal place if required. Depending on the value of the source value, one of the following results may occur:

    • If the source value is too small to be represented as a decimal, the result becomes zero.

    • If the source value is NaN (not a number), infinity, or too large to be represented as a decimal, an OverflowException is thrown.

  • When you convert decimal to float or double, the decimal value is rounded to the nearest double or float value.

For more information on explicit conversion, see Explicit in the C# Language Specification. For more information on how to access the spec, see C# Language Specification.






Formatting Numeric Results Table


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

You can format numeric results by using the String.Format method, or through the Console.Write or Console.WriteLine method, which calls String.Format. The format is specified by using format strings. The following table contains the supported standard format strings. The format string takes the following form: Axx, where A is the format specifier and xx is the precision specifier. The format specifier controls the type of formatting applied to the numeric value, and the precision specifier controls the number of significant digits or decimal places of the formatted output. The value of the precision specifier ranges from 0 to 99.

For more information about standard and custom formatting strings, see Formatting Types. For more information about the String.Format method, see String.Format.

Format SpecifierDescriptionExamplesOutput
C or cCurrencyConsole.Write("{0:C}", 2.5);

Console.Write("{0:C}", -2.5);
$2.50

($2.50)
D or dDecimalConsole.Write("{0:D5}", 25);00025
E or eScientificConsole.Write("{0:E}", 250000);2.500000E+005
F or fFixed-pointConsole.Write("{0:F2}", 25);

Console.Write("{0:F0}", 25);
25.00

25
G or gGeneralConsole.Write("{0:G}", 2.5);2.5
N or nNumberConsole.Write("{0:N}", 2500000);2,500,000.00
X or xHexadecimalConsole.Write("{0:X}", 250);

Console.Write("{0:X}", 0xffff);
FA

FFFF












'프로그래밍 > C#' 카테고리의 다른 글

Getting Started with C#  (0) 2017.02.13
클래스 종류 헤드라인  (0) 2017.01.04
helpful classes  (0) 2016.11.24
Operators  (0) 2016.11.14
IEnumerable Interface  (0) 2016.11.14
:
Posted by 지훈2