How to override default(T) in C#?

You can't override the default(T) keyword. It is always null for reference types and zero for value types.

More Information

  • MSDN - default Keyword in Generic Code (C# Programming Guide)

Doesn't seem like it. From the documentation:

default ... will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types.


Frankly, it's not a real answer but a simple mention. If Foo was a struct so you can have something like this:

public struct Foo
{

    public static readonly Foo Default = new Foo("Default text...");

    public Foo(string text)
    {
        mText = text;
        mInitialized = true;
    }

    public string Text
    {
        get
        {
            if (mInitialized)
            {
                return mText;
            }
            return Default.mText;
        }
        set { mText = value; }
    }

    private string mText;
    private bool mInitialized;

}

[TestClass]
public class FooTest
{

    [TestMethod]
    public void TestDefault()
    {
        var o = default(Foo);

        Assert.AreEqual("Default text...", o.Text);
    }

}