What is the difference between myCustomer.GetType() and typeof(Customer) in C#?

后端 未结 7 1199
渐次进展
渐次进展 2020-12-02 07:11

I\'ve seen both done in some code I\'m maintaining, but don\'t know the difference. Is there one?

let me add that myCustomer is an instance of Customer

7条回答
  •  抹茶落季
    2020-12-02 07:32

    The result of both are exactly the same in your case. It will be your custom type that derives from System.Type. The only real difference here is that when you want to obtain the type from an instance of your class, you use GetType. If you don't have an instance, but you know the type name (and just need the actual System.Type to inspect or compare to), you would use typeof.

    Important difference

    EDIT: Let me add that the call to GetType gets resolved at runtime, while typeof is resolved at compile time.

提交回复
热议问题