[Solved] C# Error: Class does not contain a constructor that takes arguments
This is a build error in C#. This error “ClassName does not contain a constructor that takes N arguments” is thrown when you do not write a constructor that accepts those number of arguments you sent while creating the object.
Example
Let us recreate a scenario in which we do not define any constructor but tried to create an object with values passed as arguments.
Program.cs
using System; namespace CSharpExamples { class Book{ public string author; public string title; public void printBookDetails(){ Console.WriteLine("\n---Book Details---\n=================="); Console.WriteLine("Title : "+title); Console.WriteLine("Author : "+author); } } class Program { static void Main(string[] args) { Book book1 = new Book("C# Tutorial", "TutorialKart"); book1.printBookDetails(); } } }
Output
Program.cs(16,30): error CS1729: 'Book' does not contain a constructor that takes 2 arguments [D:\workspace\csharp\HelloWorld\HelloWorld.csproj] Program.cs(6,23): warning CS0649: Field 'Book.title' is never assigned to, and will always have its default value null [D:\workspace\csharp\HelloWorld\HelloWorld.csproj] Program.cs(5,23): warning CS0649: Field 'Book.author' is never assigned to, and will always have its default value null [D:\workspace\csharp\HelloWorld\HelloWorld.csproj] The build failed. Please fix the build errors and run again.
ADVERTISEMENT
Solution
For this to work out we need to either add a constructor to class Book
that takes 2
arguments or create book1
object with no arguments.
using System; namespace CSharpExamples { class Book{ public string author; public string title; public Book(string Title, string Author){ title = Title; author = Author; } public void printBookDetails(){ Console.WriteLine("\n---Book Details---\n=================="); Console.WriteLine("Title : "+title); Console.WriteLine("Author : "+author); } } class Program { static void Main(string[] args) { Book book1 = new Book("C# Tutorial", "TutorialKart"); book1.printBookDetails(); } } }
Output
---Book Details--- ================== Title : C# Tutorial Author : TutorialKart
Conclusion
In this C# Tutorial, we learned how to fix C# Error: “Class does not contain a constructor that takes arguments”.