Brandon Grossutti
Brandon Grossutti

Reputation: 1271

Can you Create Your Own Default T where T is your own class

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

Answers (6)

Paul
Paul

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

Stefan Moser
Stefan Moser

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

Simon P Stevens
Simon P Stevens

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

bashmohandes
bashmohandes

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

Jonathan Rupp
Jonathan Rupp

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

Sean Bright
Sean Bright

Reputation: 120704

No. The default for classes (reference types) is null and cannot be overloaded.

Upvotes: 5

Related Questions