0

I am trying to implement char array inside the struct Books. i have declared the char array public char[] b_id = new char[3] inside the struct. Now i want to access the b_id and initialize some value. how can it be done. Any suggestions? this is my present code.

namespace @struct
{
   struct Books
    {
        public string title;
        public char[] b_id = new char[3];
    };  
class Program
{

    static void Main(string[] args)
    {

        Books Book1;        /* Declare Book1 of type Book */

       /* book 1 specification */
        Book1.title = "C Programming";


        /* print Book1 info */
        Console.WriteLine("Book 1 title : {0}", Book1.title);

        Console.ReadKey();

    }
}
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
AJ_NOVICE
  • 311
  • 1
  • 4
  • 11
  • 2
    What where your problems in accessing it in the obvious way? What errors did you get? (Putting aside for the moment that you have a mutable struct there: http://stackoverflow.com/questions/441309/why-are-mutable-structs-evil ) – HugoRune Mar 19 '15 at 07:33
  • 1
    Why are you using mutable structs and public fields at all? I would avoid doing so if possible. It's not clear that you should be using a struct in the first place... please provide more information about *why* you're doing this... (And I'd strongly recommend against using a namespace which is a keyword, too...) – Jon Skeet Mar 19 '15 at 07:35
  • Potential dupe: http://stackoverflow.com/questions/8158038/is-there-a-way-to-initialize-members-of-a-struct-without-using-a-constructor – HugoRune Mar 19 '15 at 08:01

1 Answers1

0

You can't have instance field initializers in structs (i.e. the compiler does not allow you to initialize your b_id char array directly inside the Books struct). Your program should work if you do something like:

struct Books
{
   public string title;
   public char[] b_id;
};

void Main()
{

   Books book1;        /* Declare Book1 of type Book */
   book1.b_id = new char[3] {'a', 'b', 'c'};

   /* book 1 specification */
   book1.title = "C Programming";

   /* print Book1 info */
   Console.WriteLine("Book 1 title : {0}", book1.title);
   Console.WriteLine("Book att : {0}", book1.b_id[0]);

 }
barca_d
  • 1,031
  • 2
  • 13
  • 30
  • 1
    A correct answer with a negative score? I guess downvoters are often too lazy to explain their downvotes... – Matthew Watson Mar 19 '15 at 09:01
  • Yes, I was surprised as well. Even if the questions aren't always the best, I think SO users could be a little more indulgent with people trying to learn how to program – barca_d Mar 19 '15 at 09:23