C#: System.Object vs Generics

前端 未结 8 876
别那么骄傲
别那么骄傲 2020-11-30 05:48

I\'m having a hard time understanding when to use Object (boxing/unboxing) vs when to use generics.

For example:

public class Stack 
{
    int positi         


        
相关标签:
8条回答
  • 2020-11-30 06:30

    Use generics when you want your structure to handle a single type. For example, if you wanted a collection of strings you would want to instantiate a strongly typed List of strings like so:

    List<string> myStrings = new List<string>();
    

    If you want it to handle multiple types you can do without generics but you will incur a small performance hit for boxing/unboxing operations.

    0 讨论(0)
  • 2020-11-30 06:32

    A lot of people have recommended using generics, but it looks like they all miss the point. It's often not about the performance hit related to boxing primitive types or casting, it's about getting the compiler to work for you.

    If I have a list of strings, I want the compiler to prove to me that it will always contain a list of strings. Generics does just that - I specify the intent, and the compiler proves it for me.

    Ideally, I would prefer an even richer type system where you could say for example that a type (even if it was a reference type) could not contain null values, but C# does unfortunately not currently offer that.

    0 讨论(0)
提交回复
热议问题