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.