It doesn't really make sense to have the only constructor for a class require an instance of the class, and you would definitely need some other type of constructor in order to use one (otherwise you can never create that initial instance).
One thing that does make sense, however, is to have a static method that creates a new instance of the class from an existing class.
The example below does not have any explicit constructor defined, so the default constructor is used and the class values are set explicitly:
class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public static Student CreateFrom(Student student)
{
return new Student { StudentId = student.StudentId, Name = student.Name };
}
}
To use this method, you would first create a student:
var studentOne = new Student { StudentId = 1, Name = "Bob"};
Then, to create a new student from this one, we can call our static method:
var studentTwo = Student.CreateFrom(studentOne);
But now we have two students with the same Id. Perhaps that's not really what we want, so it might be better to have an read-only StudentId that gets set automatically from a private static backing field. We can use a lock object to ensure we don't assign the same id to more than one student. Also we can override the ToString method so it displays the Id and Name of the student:
class Student
{
// This lock object is used to ensure we don't
// assign the same Id to more than one student
private static readonly object IdLocker = new object();
// This keeps track of next available student Id
private static int nextStudentId;
// Read only
public int StudentId { get; }
public string Name { get; set; }
// Default constructor automatically sets the student Id
public Student()
{
lock (IdLocker)
{
// Assign student id and incrment the next avaialable
StudentId = nextStudentId;
nextStudentId++;
}
}
public static Student CreateFrom(Student student)
{
return new Student { Name = student.Name };
}
public override string ToString()
{
return $"Student {StudentId}: {Name}";
}
}
Now we don't need to set the id, and we can see that it automatically increments for us:
private static void Main()
{
var studentOne = new Student { Name = "Bob" };
var studentTwo = Student.CreateFrom(studentOne);
Console.WriteLine(studentOne);
Console.WriteLine(studentTwo);
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
