7.8. Summary

Data types form a fundamental building block of a programming language. Whereas Java provides only a handful of data types (classes, interfaces, and primitives), C# has a rich set of value types and reference types. Both should be used in C# programming. You are encouraged not to try to model everything as a class and thereby miss out on some of the optimizations, such as structs, that are built into C# data types. The following key conclusions can be drawn from this chapter:

  • C# data types can be value types, reference types, or pointer types. Value types can be struct or enum. A struct can be user-defined or built-in. Both structs and enums are lightweight constructs that do not have an equivalent in Java.

  • C# built-in value types can be integral, floating, decimal, or Boolean. Each built-in type has an alias and a .NET class found in the System namespace.

  • Value types in C# are like Java primitives, but unlike Java primitives, they inherit from System.Object and can be treated as objects. Therefore, C# value types can be assigned literals (such as ordinary variables), or they can be constructed using the new operator.

  • In general, a built-in value type can be implicitly converted to another value type if the original data type is smaller in size than the converted data type. For example, you can assign an int literal to a long variable. Implicit conversion of a literal happens during assignment of the literal to the variable. However, an explicit cast is required when you pass the literal to a method parameter. For example, suppose you have a method that takes an sbyte. When this method is passed an integer literal, the literal will have to be cast to sbyte. Explicit casting is also required when a larger data type is being assigned to a smaller data type.

  • C# has built-in boxing and unboxing, which allows you to interchange the built-in value type aliases with their .NET class equivalents. This simplifies code, and you can simply pass primitives (in Javaspeak) to methods that require objects.

  • C# reference types are classes, interfaces, and delegates.

  • C# pointer types allow for direct pointer manipulation through the pointer data type. These data types can be used only in an unsafe context, and their use is usually discouraged unless it is absolutely required.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.182.76