Need suggestion to write a common coe in base class with T type

Pk1425 1 Reputation point
2022-11-10T23:20:07.897+00:00

public class Model1
{
public int Id; (these are properties)
public int Dx;
public int Cy;
public string Key1;
public string Key2;
}

public class Model2
{
public int Id; (these are properties)
public int Dx;
public int Cy;
public string Key1;
public string Key2;
public string Prop2;
public string Prop3;
public string Prop4;
}

public class A
{
public async Task<Model1> Save(Model1 m1)
{
//need to set key before saving the model
m1.Key1 = $"m1.Id-Dx"; // I want it to be set here only not by the caller
m1.Key2 = $"m1.Id-Cy";
//Save to Db
return m1;
}
// Likewise I have few other methods like Delete etc

}
public class B
{
public async Task<Model2> Save(Model2 m2)
{
//need to set key before saving the model
m2.Key1 = $"m2.Id-Dx"; // I want it to be set here only not by the caller
m2.Key2 = $"m2.Id-Cy";
//Save to Db
return m2;
}
// Likewise I have few other methods like Delete etc
}

Just like class A and B I have total 14 classes to write in the same fashion and same code. So instead of writing same piece of code again and again I just want to write a common class and pass the type of the model to it to build the Key (using that properties in T type) and save that model to db. Can someone suggest. (if I use T type then how do I access the properties like Key or any other in the base class)?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,627 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,496 Reputation points Microsoft Vendor
    2022-11-23T07:36:21.997+00:00

    @Pk1425 , Welcome to Microsoft Q&A, you could try the following code to write a generic class to get what you wanted.

     public class Model1  
        {  
            public int Id;   
            public int Dx;  
            public int Cy;  
            public string Key1;  
            public string Key2;  
        }  
        public class Example<T> where T : Model1  
        {  
            public  Task<T> Save(T t)  
            {  
                //need to set key before saving the model  
                t.Key1 = $"m1.Id-Dx"; // I want it to be set here only not by the caller  
                t.Key2 = $"m1.Id-Cy";  
                //Save to Db  
                return Task.FromResult(t);  
            }  
            // Likewise I have few other methods like Delete etc  
      
        }   
    

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments