I have a Student class in my console application like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Student
{
public Student(Student student)
{
StudentId = student.StudentId;
FullName = student.FullName;
}
public int StudentId { get; set; }
public string FullName { get; set; }
}
}
It has a copy constructor in its body and when I want to instantiate it in the Program class like this:
Student student = new Student();
I will have an error that
"There is no argument given that corresponds to the required formal parameter 'student' of 'Student.Student(Student)'"
When I can not instantiate my Student class how could I pass the argument of Student to its constructor ?
I want to instantiate my Student class but I've got the error on it that I described.
You mention that you would like to use a copy constructor to create a new Student
.
This requires you to have an existing Student
instance to copy from.
Moreover - as long as you only have a copy constructor you will never be able to create such an instance (because the implicit default constructor will no longer be available).
The solution is to add a constructor - either a default one (without parameters), or one that requires e.g. an int
and a String
and initializes the fields of the new instance:
// Default constructor:
public Student()
{
StudentId = -1; // some default ID
FullName = "SomeName"; // some default name
}
Or:
// Constructor with parameters:
public Student(int id, String name)
{
StudentId = id;
FullName = name;
}
(or even both).
Note that if you use the default constructor you should probably set the fields to proper values afterwards.
Only after creating an instance with such a constructor you can use your copy constructor:
// Create a default instance and then set the fields:
Student studentToCopyFrom = new Student();
studentToCopyFrom.StudentId = 111;
studentToCopyFrom.FullName = "Joe";
// Or create an instance with arguments for the fields:
Student studentToCopyFrom = new Student(111, "Joe");
// Now create a new instance with the copy constructor:
Student student = new Student(studentToCopyFrom);