© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
37 replies
big OOF

Declare method using T and where [Answered]

This is some code from a reddit post i saw and there are some thing i dont understand.

This is the method:
public static T CreateStudentFromEntity<T>(Student entity) where T : IStudent
        {
            var student = Activator.CreateInstance<T>();

            student.Id = entity.Id;
            student.FirstName = entity.Name;
            student.Surname = entity.Surname;
            student.DateOfBirth = DateTime.Parse(entity.DateOfBirth);
            student.Sex = (Sex)entity.Sex;
            student.Address = CreateAddressFromEntity(entity.Address);

            return student;
        }
public static T CreateStudentFromEntity<T>(Student entity) where T : IStudent
        {
            var student = Activator.CreateInstance<T>();

            student.Id = entity.Id;
            student.FirstName = entity.Name;
            student.Surname = entity.Surname;
            student.DateOfBirth = DateTime.Parse(entity.DateOfBirth);
            student.Sex = (Sex)entity.Sex;
            student.Address = CreateAddressFromEntity(entity.Address);

            return student;
        }

This is the interface that the method uses:
public interface IStudent
{
    long Id { get; set; }
    string? FirstName { get; set; }
    string? Surname { get; set; }
    DateTime DateOfBirth { get; set; }
    Sex Sex { get; set; }
    string? TelephoneNumber { get; set; }
    Address? Address { get; set; }
}
public interface IStudent
{
    long Id { get; set; }
    string? FirstName { get; set; }
    string? Surname { get; set; }
    DateTime DateOfBirth { get; set; }
    Sex Sex { get; set; }
    string? TelephoneNumber { get; set; }
    Address? Address { get; set; }
}

From what i understand, T is used to be able to make the method more "flixble", not restricting it to a specific return type.

But when adding "where T : IStudent" - it restricts it to only return a object that inherits the IStudent interface?

Could you not just replace T with IStudent and skip the where?

Plase let me know if i got in wrong 🙂

Thanks in advance!
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

using generic method without knowing T
C#CC# / help
3y ago