What does default(object); do in C#?

后端 未结 9 2311
误落风尘
误落风尘 2020-11-28 03:03

Googling is only coming up with the keyword, but I stumbled across some code that says

MyVariable = default(MyObject);

and I am wondering

9条回答
  •  旧巷少年郎
    2020-11-28 03:30

    Perhaps this may help you:

    using System;
    using System.Collections.Generic;
    namespace Wrox.ProCSharp.Generics
    {
        public class DocumentManager < T >
        {
            private readonly Queue < T > documentQueue = new Queue < T > ();
            public void AddDocument(T doc)
            {
                lock (this)
                {
                    documentQueue.Enqueue(doc);
                }
            }
    
            public bool IsDocumentAvailable
            {
                get { return documentQueue.Count > 0; }
            }
        }
    }
    

    It is not possible to assign null to generic types. The reason is that a generic type can also be instantiated as a value type, and null is allowed only with reference types. To circumvent this problem, you can use the default keyword. With the default keyword, null is assigned to reference types and 0 is assigned to value types.

    public T GetDocument()
    {
        T doc = default(T);
        lock (this)
        {
            doc = documentQueue.Dequeue();
        }
        return doc;
    }
    

    The default keyword has multiple meanings depending on the context where it is used. The switch statement uses a default for defining the default case, and with generics the default is used to initialize generic types either to null or 0 depending on if it is a reference or value type.

提交回复
热议问题