How do I write a property for a list inside of a struct?
my code:
public struct Config
{
List<int> ipAddress = new List<int>();
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If all you want is to create an auto-property (which will default to
nullfor reference types and cannot be initialized) you can do as @scartag suggests.However, if you’re trying to do what’s in your code and initialize it to an actual reference, you will run into issues because you can’t initialize fields in a
struct. They can only have their defaults. To make matters even worse, you can’t override a default constructor to do this for you.Generally speaking,
structtends to be best for small, preferably immutable types. Is there a reason you don’t want to just useclassfor this?Now, if you did want to create a
structwith an “initialized” field, you can fool it with some lazy logic:But really, at this rate it’s better to use a
classsince you can initialize fields, or override the default constructor:And again, as Andrew mentioned in the comments, I strongly suggest looking at MSDN guidance on choosing between
structandclass