1

I'm new to C#, so this problem may be trivial to many of you... I'm writing simple application that uses API of a certain website. I'm using and altering an example from this website. So the problem is when I'm instantiating an object that (in simple words) returns simple variable like string, int or even user-defined type everything seems to be working fine, but when I try to instantiate an element that is an element array of user-defined:

    request.@parameters.examplename = new somenamespace.SomeName.UserType();

type I get a message like this:

    "Cannot implicitly convert type "somenamespace.SomeName.UserType' to 'somenamespace.SomeName.UserType[]'."

Can you explain to me what am I doing wrong? Is there a different way to instantiate an element array? If you need more information please let me know.

Thanos Markou
  • 2,587
  • 3
  • 25
  • 32
Deuces
  • 97
  • 5
  • possible duplicate of [All possible C# array initialization syntaxes](http://stackoverflow.com/questions/5678216/all-possible-c-sharp-array-initialization-syntaxes) – Stephen Kennedy Jul 15 '15 at 12:53

2 Answers2

2

You should change your line to:

request.@parameters.examplename = 
    new somenamespace.SomeName.UserType[] { new somenamespace.SomeName.UserType() };

You are currently trying to assign a single UserType value to something that wants an array of UserType's. So this is solved by creating an array (the new[] part) and populating it with the UserType value (the {} part).

David Arno
  • 42,717
  • 16
  • 86
  • 131
1

Given your error output it looks like your syntax is incorrect. You have a UserType array (UserType[]) called request.@parameters.examplename which you are attempting to assign a UserType object to; new UserType() calls the constructor on the object.

What you require is a newly instantiated array of UserTypes:

request.@parameters.examplename = new somenamespace.SomeName.UserType[];

Wibbler
  • 1,020
  • 9
  • 17
  • Yes the array will be empty, but his question does not state that he requries the array be populated; only that it be instantiated. – Wibbler Jul 15 '15 at 10:34
  • 1
    And then the very next question from @Deuces will be "why do I get an index out of bounds error when I try to access an element of my array?". SO isn't supposed to be a service for blindly answering questions; the answers should seek to answer the more general question so that they are useful to others in future too. – David Arno Jul 15 '15 at 10:52
  • If you suspect @Deuces will be confused by populating the array later, asking for clarification of the intention of his question rather than making an assumption would be more useful wouldn't it? Answering the question asked rather than the one you think he _wants_ to ask? – Wibbler Jul 15 '15 at 11:40