validate that a book has author snd correct isbn in csharp

To validate that a book has an author and a correct ISBN in C#, you can define a Book class with properties for the author and the ISBN. You can then write a validation method that checks if the author is not null or empty, and if the ISBN is a valid 10-digit or 13-digit number.

main.cs
public class Book
{
    public string Author { get; set; }
    public string ISBN { get; set; }
}

public bool ValidateBook(Book book)
{
    // Check if author is null or empty
    if (string.IsNullOrEmpty(book.Author))
    {
        return false;
    }
    
    // Check if ISBN is a valid 10-digit or 13-digit number
    string isbn = book.ISBN.Replace("-", ""); // Remove hyphens, if any
    if (isbn.Length == 10)
    {
        int sum = 0;
        for (int i = 0; i < 9; i++)
        {
            sum += (i + 1) * int.Parse(isbn[i].ToString());
        }
        int rem = sum % 11;
        if (rem == int.Parse(isbn[9].ToString()) || (rem == 10 && isbn[9] == 'X'))
        {
            return true;
        }
    }
    else if (isbn.Length == 13)
    {
        int sum = 0;
        for (int i = 0; i < 12; i++)
        {
            sum += ((i % 2 == 0) ? 1 : 3) * int.Parse(isbn[i].ToString());
        }
        int rem = sum % 10;
        int check = (rem == 0) ? 0 : (10 - rem);
        if (check == int.Parse(isbn[12].ToString()))
        {
            return true;
        }
    }
    
    return false;
}
1120 chars
47 lines

You can then use the validation method to check if a given book object has a valid author and ISBN:

main.cs
Book book = new Book { Author = "John Doe", ISBN = "978-3-16-148410-0" };
bool isValid = ValidateBook(book);
Console.WriteLine(isValid); // true
145 chars
4 lines

gistlibby LogSnag