简体   繁体   中英

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!

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM