0

I'm really new to c# coming from c++ background I'm struggling to work with data structures in c++ I used to do that for example

struct product {
  int weight;
  double price;
} apple[10];

now the problem c# won't let me do the same because in c# when I declare an object type like apple I can't access the weight or the price now . is there a way to declare object type array ? like above I know I can do that

product apple = new product();

but I receive an error cannot apply indexing with [] to an expression of type Program.product . is there a way to apply indexing with data structures all I want to do is something like this .

struct product {
  int x;
  double w;
} array[10];

for (int i = 0 ; i < 5 ; i++ ){

array[i].x = array[i - 1].x

}

I appreciate your help.

1
  • 4
    Be aware that the difference between struct and class in .NET is far more important than the difference between the two in C++. They use the same names but they are not the same concepts. Commented Nov 12, 2019 at 16:44

1 Answer 1

1

Members variables are private by default in C#, so you need to add public before type and name.

Also to create an array you need to use the new keyword.

public struct product 
{
  public int x;
  public double w;
}

var products = new product[10];

for (int i = 1 ; i < 5 ; i++ )
{
  products [i].x = products [i - 1].x; // beware 0-1 = -1
}

Instances of structs are value types, instead of instances of classes that are references to objects (hidden managed pointers to forget to manage them).

This may help you:

struct (C# Reference)

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

2 Comments

Thanks It's working exactly what I wanted but sometimes depending on the source code I get an error saying the contextual keyword var may only appear within a local variable declaration or in script mode
Yes, var cannot be used in the scope of a class or a struct. It's a syntactic sugar for local variables when the compiler can infer the type from the right part of the assignment expression: var (C# Reference).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.