How can I create a C # class to create another class in its constructor?

I created the following:

public class HttpStatusErrors { public HttpStatusErrors() { this.Details = new List<HttpStatusErrorDetails>(); } public string Header { set; get; } public IList<HttpStatusErrorDetails> Details { set; get; } } public class HttpStatusErrorDetails { public HttpStatusErrorDetails() { this.Errors = new List<string>(); } public string Error { set; get; } public IList<string> Errors { set; get; } } 

In my code, I use it as follows:

 var msg = new HttpStatusErrors(); msg.Header = "Validation Error"; foreach (var eve in ex.EntityValidationErrors) { msg.Details. // Valid so far msg.Details.Error // Gives the error below: 

Ide recognizes msg.Details as valid, but when I try to write the second line, I get:

 Error 3 'System.Collections.Generic.IList<TestDb.Models.Http.HttpStatusErrorDetails>' does not contain a definition for 'Error' and no extension method 'Error' accepting a first argument of type 'System.Collections.Generic.IList<TestDb.Models.Http.HttpStatusErrorDetails>' could be found (are you missing a using directive or an assembly reference?) C:\K\ST136 Aug 16\WebUx\Controllers\ProblemController.cs 121 33 WebUx 

Is there something I'm doing wrong? I thought how I determined that new lists would be created when creating the first class.

+4
source share
3 answers

msg.Details returns a List object. List<T> does not have the Errors property. You need to access a specific item in your list, and only then will you have your Errors property.

For instance:

 msg.Details[0].Error 

In your code, you can verify that msg.Details contains elements before trying to access them, or better yet, msg.Details over them in a foreach .

+11
source

Details is a collection. The Error property belongs to an element in the Details collection. There is no Error property in this collection. Details

+1
source

you bind to Details , which is IList<HttpStatusErrorDetails> .

if you want to go through the items in this list, you need to go through them for example

 msg.Details[number].Errors 

or

 foreach(HttpStatusErrorDetails err in msg.Details) { err.Errors } 
+1
source

Source: https://habr.com/ru/post/1497213/


All Articles