C# void type- safety

前端 未结 5 1854
眼角桃花
眼角桃花 2021-02-10 04:24

I am just new for C# programming (coming from C++)

My question is: In C# every type inherits from Object Why \'void\' doesn`t?Can it cause some RT/type safety problems

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-10 04:37

    Void is a Type, but methods that return void, don't push anything onto the stack. System.Void is declared as a struct, so it should inherit from object, too, but it's handled differently. You can see it clearer if you look at the IL code, after a method returning void is called, there is no pop instruction, which normally is used to pop unused return values off the stack.

    EDIT: Actually, i checked. If i declare a method as returning System.Void, i get an error message stating that System.Void can't be used from C# code. But try the following:

    typeof(object).IsAssignableFrom(typeof(void))
    typeof(System.ValueType).IsAssignableFrom(typeof(void))
    

    that will return true, so void does derive from object and System.ValueType (i.e. struct)

提交回复
热议问题