2

In here I can't use foreach:

`Error CS0030 Cannot convert type 'ConsoleApplication5._3.Struct.Sach' to 'int'

How can I fix it?

public struct Sach
{
    public string TenSach;
    public string TacGia;
    public string GioiThieu;
    public int ID;
    public void nhapdulieu(string q,string w, string e, int r)
    {
        TenSach = q;
        TacGia = w;
        GioiThieu = e;
        ID = r;
    }
    public void Insach()
    {
        Console.Write($"Ten sach: {TenSach}\n");
        Console.Write($"Tac gia: {TacGia}\n");
        Console.Write($"Gioi thieu: {GioiThieu}\n");
        Console.Write($"Ma sach: {ID}\n");
    }
};


public class QuanLySach
{
    public static void NhapSach()
    {

        Sach[] sach1 = new Sach[4];
        for(int i=0;i<4;i++)
        {
            Console.WriteLine("nhap ten sach, tac gia, gioi thieu, id:");
            sach1[i].TenSach = Console.ReadLine();
            sach1[i].TacGia = Console.ReadLine();
            sach1[i].GioiThieu = Console.ReadLine();
            var vv = Console.ReadLine();
            Int32.TryParse(vv, out sach1[i].ID);
        }

        foreach(int bb in sach1)
        {
         // in here i cant use foreach but i dont know why?
        }
        Console.ReadLine();
    }  
    }
}
1
  • a foreach loop contains an Inner Cast of the Collection[index] to your item's Type. in other words your foreach( int bb in sach1) tells the compiler that each sach1 item is an int, while it is not. thats why you get the error. i suggest you read this book amazon.com/Exam-Ref-70-483-Programming-MCSD/dp/0735676828 Commented Feb 14, 2017 at 5:12

1 Answer 1

2

You are using foreach incorrectly. Foreach loop will iterate trough sequence and your bb should be same type as base type for that sequence. In your case it should be:

foreach(Sach bb in sach1)
{
     // in here i cant use foreach but i dont know why?
}
Sign up to request clarification or add additional context in comments.

5 Comments

Also, beware, you can only read data from bb. not write to it.
@bwoogie Exactly, he will need to generate new collection of Sach except if he want to update only fields of bb and he doesn't want to change sach1.
@VôTâm No problem. Does this post solved an issue? If solved can you please mark as answered?
i can fix this error :D and how to mark as answered?
:) Just click "OK" icon on the left side. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.