开发者

C# struct partially initialization

开发者 https://www.devze.com 2023-02-22 09:07 出处:网络
I have a parameters struct: public struct MyParams { public intParam1; public intParam2; public string Param3;

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 advan开发者_如何学Goce!


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;

0

精彩评论

暂无评论...
验证码 换一张
取 消