-1

Please help anyone. This is my first question on this site.

I am a very beginner in C#, learning a little bit about C# structures. Here I have two source codes in C# with structures.

The first one is about a structure having record of two books such as Book Name, Author Name, Page No and Book ID. Here, in line 17, I declared two types of Book to access the members of the structures but not used the "new" operator. However, it compiled succesfully and gave the correct output.

Source Code 1 :

using System;

namespace StructureTest
{
    struct Book
    {
        public string name;
        public string author;
        public int page_no;
        public int book_id;
    }

    class Program
    {
        static void Main(String[] args)
        {
            Book Book1, Book2;

            Book1.name = "Programming in ANSI C";
            Book1.author = "E Balagurusamy";
            Book1.page_no = 450;
            Book1.book_id = 34567821;

            Book2.name = "C Programming";
            Book2.author = "Tamim Shahriar Subeen";
            Book2.page_no = 280;
            Book2.book_id = 34567477;

            Console.WriteLine("Book1 Name = {0}", Book1.name);
            Console.WriteLine("Book1 Author Name = {0}", Book1.author);
            Console.WriteLine("Book1 Total Page No = {0}", Book1.page_no);
            Console.WriteLine("Book1 ID = {0}", Book1.book_id);

            Console.WriteLine("Book2 Name = {0}", Book2.name);
            Console.WriteLine("Book2 Author Name = {0}", Book2.author);
            Console.WriteLine("Book2 Total Page No = {0}", Book2.page_no);
            Console.WriteLine("Book2 ID = {0}", Book2.book_id);

            Console.ReadKey();
        }
    }
}

But in the second code, I differently declared two functions in that structure and use them to take the values of the records and print those as output. But surprisingly, the code didn't compiled showing these error messege,

prog.cs(39,13): error CS0165: Use of unassigned local variable `book1'

prog.cs(43,13): error CS0165: Use of unassigned local variable `book2'

Source Code 2 :

using System;

namespace StructureWithMethods
{
    struct StructureMethods
    {
        public string name;
        public string author;
        public int page;
        public int id;

        public void setvalue(string a, string b, int c, int d)
        {
            name = a;
            author = b;
            page = c;
            id = d;
        }

        public void printinfo()
        {
            Console.WriteLine("Name : " + name);
            Console.WriteLine("Author : " + author);
            Console.WriteLine("Total Page No : " + page);
            Console.WriteLine("ID : " + id);
        }
    }

    class Program
    {
        static void Main(String[] args)
        {
            StructureMethods book1,book2;

            book1.setvalue("Aaj Himur Biye", "Humayun Ahmed", 232, 45771256);
            Console.WriteLine("1st Book Record :");
            book1.printinfo();

            book2.setvalue("Raju O Agunalir Bhoot", "Md. Zafar Iqbal", 198, 45777129);
            Console.WriteLine("\n2nd Book Record :");
            book2.printinfo();

            Console.ReadKey();
        }
    }
}

But, however after sometime I managed to use "new" keyword when declaring the type of struct Book and then it compiled succesfully and gave the correct output.

Now, my question is, Should I use "new" in structures while declaring methods only? Or is it mandatory to use "new" in structures while creating an object? But my first code compiled succesfully.

Community
  • 1
  • 1
Shah Shishir
  • 161
  • 2
  • 4
  • 13
  • We have no shortage of questions on Stack Overflow discussing proper initialization of `struct` types used as local variables. See marked duplicates for a few examples, including the third which includes details from the specification regarding the specific requirements for "definite assignment". – Peter Duniho Apr 15 '17 at 18:50

2 Answers2

3

Should I use "new" in structures

Here is some useful information from MSDN:

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. In such a case, there is no constructor call, which makes the allocation more efficient. However, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

So your first code compiled without error because you assigned all the fields and then you used the object.

The second code fails because the struct object cannot be used since you have not used the new operator or assigned all the fields yet, so you cannot use the object yet and call methods on it.

For example, in the code below new operator is not used but it works because all the fields have been initialized:

class Program
{

    static void Main(string[] args)
    {
        A a;
        a.X = 1;
        a.Print();
        Console.Read();
    }
}

struct A
{
    public int X;
    public void Print()
    {
        Console.WriteLine("A has X: {0}", this.X);
    }
}

However, the code below will not work because the fields have not been initialized:

class Program
{

    static void Main(string[] args)
    {
        A a;
        //a.X = 1; <------ SEE this is commented out
        a.Print();
        Console.Read();
    }
}

struct A
{
    public int X;
    public void Print()
    {
        Console.WriteLine("A has X: {0}", this.X);
    }
}

So in conclusion, you must either:

  1. Initialize all the fields and then you can use the object
  2. Use the new operator to invoke the constructor and then use the object.

Please note this only applies to structs and not classes. For classes, you can only use the static members without the new operator and to use the object of a class, you will have to use the new operator.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
2

Although you don't need the new to instantiate a structure, the compiler will not let you use any method or property unless all of its fields are initialized.

You can either create a constructor instead of the setvalue method, or assign it one after the other:

StructureMethods book1;
book1.author = "ds";
book1.name = "";
book1.page = 1;
book1.id = 3;
book1.printinfo();

StructureMethods book2 = new StructureMethods("test","bbb",0,1);
book2.printinfo();

struct StructureMethods
{
    public string name;
    public string author;
    public int page;
    public int id;

    public StructureMethods(string a, string b, int c, int d)
    {
        name = a;
        author = b;
        page = c;
        id = d;
    }

    public void printinfo()
    {
        Console.WriteLine("Name : " + name);
        Console.WriteLine("Author : " + author);
        Console.WriteLine("Total Page No : " + page);
        Console.WriteLine("ID : " + id);
    }
}

Side-Note1: there is no need to use return; at the end of the function unless you are returning some value in a non-void method.

Side-Note2: Since you mentioned you are new to C#, be sure you understand when to use structs and when classes. You can start here

Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27