简体   繁体   中英

difference between object parameter and generic parameter(type parameter)

I was thinking about the difference between object parameter and generic parameter?

public foo<T>(T abc)

public foo(object abc)

Actual both are kind of variable and I could convert many Object into anything I like to, because its the base class everything

Whatare te difeerences?

Generics are complex topic and I would suggest you to dive deeper if you don't understand the difference.

In short: by using object you exposes yourself to run-time exceptions when you expect object to be of type A but in fact it is of type B. Generics are there to provide type safety by removing the duty of creating many eg functions doing the same thing for many different types. By using genetric constraints you can create powerful and safe solutions.

Further reading:

https://msdn.microsoft.com/library/d5x73970.aspx?f=255&MSPPError=-2147217396 https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

performance - when converting value type to object, boxing and unboxing are very expensive. type safe - need to cast objects, you lose compile-time type safety.

generics solve this issues.

it's hard to tell difference without seeing your methods . If your methods are just writing the type of inputs to console, there is no difference. But if your methods are casting object and doing something there are differences.

Generics are very powerful because of constraints and they can inherit from other generics type.

So General Difference:

Type Safety: you can send anything, but while casting you can get error at runtime with objects. if you use constraints you will get error at compile time with generics.

Cleaner Code: you will always use casting with object. You don't have to do this with generics.

Better Performance (For Value Types): there will be no boxing and unboxing with generics. if you send value type, it will first put this memory heap (boxing) then it will get to thread stack from memory heap (unboxing) with object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM