locked
Array of Struct in C# RRS feed

  • Question

  • Hi,

    I am new to C# and I need to declare an array of struct. What is the equivalent of this in c#.

    typedef struct {
    LONG GenerationGap;
    LPTSTR AncestorName;
    } INHERITED_FROM,
    *PINHERITED_FROM;

    Thanks,
    Ramya
    Saturday, May 3, 2008 12:39 AM

Answers

  • Here's how to declare the struct: (C# structs cannot be inherited, by the way, except from interfaces.)

    Code Snippet

    struct MyStructNameGoesHere

    {

    long GenerationGap;

    string AncestorName;

    }

     

    Here's how to declare the array of struct:

     

    Code Snippet

    MyStructNameGoesHere[] myStructArray = new MyStructNameGoesHere[30]; // creates an array of 30 structs. 

     

     

    To access the members of a struct, you can call:

     

    Code Snippet

    myStructArray[15]; // accesses the 16th item in the array.

     

    Note that an array in C# doesn't automatically resize, so you'll have to copy the items to a new array, or lookup List<T> on MSDN and use that instead.

    Saturday, May 3, 2008 12:47 AM
    Moderator