How to override default(T) in C#? [duplicate]

2019-02-21 11:49发布

Possible Duplicate:
Howto change what Default(T) returns in C#

print(default(int) == 0) //true

Similarly if I have a custom object, its default value will be null.

print(default(Foo) == null) //true

Can I have a custom value for default(Foo) and not null?

For example, something like this:

public static override Foo default()
{
    return new Foo();
}

This wont compile. Thanks..

3条回答
爷的心禁止访问
2楼-- · 2019-02-21 12:11

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);
    }

}
查看更多
SAY GOODBYE
3楼-- · 2019-02-21 12:33

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.

查看更多
太酷不给撩
4楼-- · 2019-02-21 12:35

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

More Information

查看更多
登录 后发表回答