0

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!

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow. It seems that I have been temporary confused with struct initialization. Its really possible to call FunctionX(new MyParams{Param2=0}); and bee happy. Thank you for ansver!
So the answer would be yes, you can
Calling FunctionX(new MyParams() {Param2=0}); would be identical to FunctionX(new MyParams());
2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.