Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have two classes candidateComments and jobscomment derived from comment table both having individual candidateId and JobId respc.

I im trying to save the comments in a post method using function

C#
public bool post(T model,Int id)
{

    //code to set common fields 
    //code to check which type using type of
    
    if(typeof(model)==typeof(candidatecomment))
    {
        model.candiateId=id;// i get error here as the model at compile time doesnt knw whether it is candidatecomment or job comment.
    }else
    {
        model.jobid =id
    }
}


Is there a way i can set the compiler to postpone the type checking at runtime ??
Posted
Updated 5-Nov-13 7:07am
v2

1 solution

What you are probably wanting to do is this:

C#
public bool post(T model,Int id)
{
 
    //code to set common fields 
    //code to check which type using type of
    
    if(model is candidatecomment)
    {
        ((candidatecomment)model).candidateId = id;
    }else
    {
        ((jobcomment)model).jobid = id;
    }
}


[Edit]
To answer your other question, yes, there is a way to disable type checking at runtime, but its a bit dirty:

C#
public bool post(dynamic model,Int id)
{
 
    //code to set common fields 
    //code to check which type using type of
    
    if(model is candidatecomment)
    {
        model.candidateId = id;
    }else
    {
        model.jobid = id;
    }
}


The keyword dynamic basically means that the compiler will not check the type of the data until runtime. This is dirty because Intellisense won't work on the model (so typing model. won't bring up a hint menu), and you have to get the spelling and capitalization right by memory. I would avoid this in favor of the one on top.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 5-Nov-13 20:53pm    
Right, 5ed. Comparison types for equivalence is a questionable thing, should be used be someone who understand the issue perfectly.
—SA
Ron Beyer 5-Nov-13 21:06pm    
Thanks Sergey.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900