官术网_书友最值得收藏!

Explicit casting with inferred variables

Imagine that a co-programmer assigned 29 to an inferred local variable (let's say age), assuming that the compiler would infer the type of the variable age as byte:

var age = 29;           // inferred type of age is int 

However, the compiler would infer the type of the variable age as int, since the default type of an integer literal value is int. To fix the preceding assumption, you can either use the explicit data type or override the compiler's default inference mechanism by using explicit casting, as follows:

byte age = 29;                // Option 1 - no type inference 
var age = (byte)29; // Option 2 - explicit casting
By using explicit casting type inference, you can override the compiler's default type inference mechanism. This might be required to fix the assumptions in the existing code. 

Similarly, you can use explicit casting with other primitive data types, like char and float:

var letter = (char)97;        // inferred type of letter is char 
var debit = (float)17.9;      // inferred type of debit is float  

Without the explicit casting in the preceding examples, variables that are assigned integer literal values would be inferred as int, and decimal as double.

The following example shows explicit casting with reference variables:

class Automobile {} 
class Car extends Automobile { 
    void check() {} 
} 
class Test{ 
    public static void main(String[] args) { 
        var obj = (Automobile)new Car();                             
        obj.check();     // Won't compile; type of obj is Automobile 
    } 
} 
Use explicit casting with type inference to fix any existing assumptions. I wouldn't recommend using explicit casting to initialize inferred variables; it defeats the purpose of using var.
主站蜘蛛池模板: 白水县| 南城县| 福贡县| 邛崃市| 甘德县| 阳泉市| 武夷山市| 原阳县| 始兴县| 蓬安县| 浠水县| 库尔勒市| 北京市| 海淀区| 中江县| 安溪县| 抚宁县| 德钦县| 曲阜市| 平阴县| 克什克腾旗| 巴马| 余庆县| 永城市| 辛集市| 嘉祥县| 特克斯县| 依安县| 云浮市| 清水河县| 宜宾县| 遵义市| 密山市| 漳州市| 通城县| 佛坪县| 西乌| 安丘市| 遵义县| 乡城县| 盈江县|