re-re
re-re

Reputation: 11

Converting object to specified class

I'm trying to make a global interface that will receive different type of class. how do I convert.

how do I pass and get an object and convert it to specific class

public void Generate()
{
 Student s = new Student
{
 Id = Entry; // binded entry
};
 var student = method("Student",s)
   if(student != null)
{
 //binded labels
   Name = Student.Name;
   Gender = Student.Gender;
   Age = Student.Age;
   Course = Student.Course;
}
}


public async Task<object> method(string condition,object obj)
{
  switch(condition)
{
   case "Student":
         var student = get from database where id= obj.id;
         return student;
   case "Teacher":
         var teacher = get from database where id= obj.id;
         return Teacher;
}

}

The question is how do I convert the passed object into a specific type of class to use it for querying into database. Same as returned value

Upvotes: 1

Views: 231

Answers (2)

Luca Q
Luca Q

Reputation: 36

You could use pattern matching on "method" to cast the passed object to use it for querying into database

public async Task<object> method(object obj)
{
    switch (obj)
    {
        case Student student:
            return (Student)null; // return  get from database where id = student.id;
        case Teacher teacher:
            return (Teacher)null; // return  get from database where id = teacher.id;
        default:
            break;
    }
}

And then

var s = new Student() { Id = 1 };
var result = await method(s);

if(result is not null && result is Student student)
{
    //binded labels
    //        Name = Student.Name;
    //        Gender = Student.Gender;
    //        Age = Student.Age;
    //        Course = Student.Course;
}

Upvotes: 1

Mohammad Azizkhani
Mohammad Azizkhani

Reputation: 342

you can cast it to specific object that you want

case "Student":
         var student = (obj as Student);
         var res = get from database where id= student?.id;
         return res;

and after call this method in you have to do it again :

var student = (method("Student",s).Result) as Studednt;

Upvotes: 3

Related Questions