Anton Semenov
Anton Semenov

Reputation: 6347

C# struct partially initialization

I have a parameters struct:

public struct MyParams
{
   public int    Param1;
   public int    Param2;
   public string Param3;
   public string Param4;
}

This is a common structure to use across application. And there are some situation in wich I need initialize only one member, all another is not used. I can Initialize struct this way:

MyParams testParams = default(MyParams);
testParams.Param2 = 3;
FunctionX(testParams);

Also I can initialize struct direct in function call, but in this case I must specify values for all members:

FunctionX(new MyParams{Param1=0,Param2=3,Param3=string.Empty,Param4=string.Empty});

My question is Can I Initialize structure in function call line and specify only one sufficient for me member and another members will take default value

Thanks in advance!

Upvotes: 0

Views: 975

Answers (2)

Jaymz
Jaymz

Reputation: 6358

When initializing a struct, all members will be initialized to their default values:

MyParams p = new MyParams() { Param3 = "Test" };

This will leave you with:

Param1 == 0;
Param2 == 0;
Param3 == "Test";
Param4 == null;

Upvotes: 2

Simon Mourier
Simon Mourier

Reputation: 139286

From 11.3.4 Default values

I quote:

However, since structs are value types that cannot be null, the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null.

Upvotes: 3

Related Questions