Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..

like image 263
nawfal Avatar asked Oct 09 '12 05:10

nawfal


People also ask

Can you override a struct?

* Structs have statically-dispatched methods and properties; there's no ability to override.

What does default t do?

Default represents default value of T parameter in generics intructions. In several cases, the default keyword is an absolute unknown and we think it's unnecessary or its functionality is null. There are many development moments with the generics classes where the default keyword can be useful.


Video Answer


1 Answers

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)
like image 74
dknaack Avatar answered Sep 19 '22 21:09

dknaack