Anton Semenov
Anton Semenov

Reputation: 6347

Is It possible to force operator **default(MyStructType)** initialize struct with predefined values

I have a struct type:

struct test1
{            
  public int a;
  public int b;
  public double c;
  public string d;
}

following line gives me "clear" struct object wich fields was initialized with their default values:

test1 tt = default(test1);
// tt.a will be equal 0

But now, I desire to have opportunity predefine default values for some fields in the struct type. For example, I want field a to have 25 as a default value.

Is it possible to force default operator initialize my struct with my predefined default values?

Upvotes: 3

Views: 115

Answers (2)

Yaur
Yaur

Reputation: 7452

Your fields will be initialized to the default value for their type, but you can use a property to make it behave as if it was setting default values.

In this snippet we use a nullable int but expose an int. If the value of the backing field is null we know that we are dealing with a new/default instance and need to provide default values.

    struct test1
    {
        private int? a;

        public int A
        {
            get { return a ?? 25; }
            set { a = value; }
        }
    }

Upvotes: 1

Oded
Oded

Reputation: 498904

No it is not possible.

The different types already have clear defaults:

  • null for reference types.
  • 0 or 0.0 for integer and float types.

I believe that the default DateTime is simply the interpretation of the above for its internal fields (0 * 100 nanoseconds from epoch).

You can't override or change how the default operator works.

Upvotes: 1

Related Questions