Reputation: 1271
lets say I have the following
public class A
{
private string _someField;
public string SomeField { get { return _someField; } }
}
For some reason I am checking the default of this class and I would like to set the default for a class, just like a default of type int is 0, I would like in the above class for my default of Somefield to be "hello";
int i = default(int); // i is 0
A myClass = default(A);
string s = myClass.SomeField; // s is hello
This is more just for my own theoretical satisfaction rather than practical application. Just wondering.
Upvotes: 2
Views: 347
Reputation: 3163
While default() will always return null, you could use where to specify that the class must contain a parameterless constructor, so you can call new on it.
void SomeMethod<T>(T something) where T : new()
{
T newObject = new T();
}
Upvotes: 0
Reputation: 6892
There is no way of overloading default(T).
To me, it really sounds like you're asking for non-nullable reference types which don't yet exist in .NET. Have a look here for an implementation: http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/non-nullable-reference-types.aspx
Upvotes: 3
Reputation: 27509
This should do the job:
public class A
{
private string _someField = "hello";
public string SomeField { get { return _someField; } }
}
Now when you create an instance of that class, the initial value of someField will be hello.
[Edit: This doesn't do quite what you want. Like others have noted in the comments, default(T) where T is a class will always result in null.
Instead you would create the class normally instead of using the 'default' keyword.
A myClass = new A();
string defaultValue = myClass.SomeField // This will be set to "hello" by default.
]
Upvotes: -1
Reputation: 2376
In case of classes (reference types) the default keyword doesn't do anything for the members of the class, it just sets the whole reference to null
Upvotes: 0
Reputation: 15772
You cannot change what default(T) is for a T. It is always null for reference types, and the 'empty' value for value types (ie. for a struct, all members are at their default, uninitalized values).
Upvotes: 5
Reputation: 120704
No. The default for classes (reference types) is null
and cannot be overloaded.
Upvotes: 5